Api: Laravel 5.5 always response json when wrong middleware or request.

Created on 18 Oct 2017  Â·  5Comments  Â·  Source: dingo/api

| Q | A
| ----------------- | ---
| Bug? | yes
| New Feature? | no
| Framework | Laravel
| Framework version | 5.5.y
| Package version | app
| PHP version | 7.0.*

Actual Behaviour

I am using laravel for web and write api for mobile, after installed dingo, if i access to web (wrong middleware ) or post wrong info (wrong validation), the system always return json error.

It redirect to back with errors before.

Middleware auth
{"status":false,"message":"Unauthenticated.","status_code":500} => it should redirect to login page

wrong validation
{"status":false,"message":"The given data was invalid.","status_code":500} => it should redirect to back with errors

Thank you.

Most helpful comment

Change
use Illuminate\Foundation\Http\FormRequest;
To
use Dingo\Api\Http\FormRequest;

All 5 comments

@dzung1nguyen Any luck with this issue?
I am having similar issue, always get 500 error if validation is failed to pass.
Thanks.

@imranali1 No :(. Let me find solution and notify for you.

I stuck with 5.4 for the sake of not breaking the app.

@imranali1
For my site, i has fixed it.

  • {"status":false,"message":"Unauthenticated.","status_code":500} => it should redirect to login page
    => Remove key API_DOMAIN in .env
  • {"status":false,"message":"The given data was invalid.","status_code":500} => it should redirect to back with errors

Create a trait:

<?php
namespace App\Traits;

use Dingo\Api\Exception\ResourceException;
use Illuminate\Contracts\Validation\Validator;

trait ApiRequestTrait
{
    /**
     * {@inheritdoc}
     */
    protected function failedValidation(Validator $validator)
    {
        if ($this->is(config('api.prefix') . '/*') && (($this->ajax() && ! $this->pjax()) || $this->wantsJson())) {
            throw new ResourceException('Yêu cầu không hợp lệ', $validator->getMessageBag());
        }

        parent::failedValidation($validator);
    }
}

// In API Request use:

<?php

namespace App\Http\Requests\Api;

use App\Traits\ApiRequestTrait;
use Illuminate\Foundation\Http\FormRequest;

class AuthLoginRequest extends FormRequest
{
    use ApiRequestTrait;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            "email" => "required|email",
            "password" => "required|min:6"
        ];
    }
}

Change
use Illuminate\Foundation\Http\FormRequest;
To
use Dingo\Api\Http\FormRequest;

Was this page helpful?
0 / 5 - 0 ratings