How to force FormRequest return json in Laravel 5.1?

别说谁变了你拦得住时间么 提交于 2019-11-27 19:45:19

It boggles my mind why this is so hard to do in Laravel. In the end, based on your idea to override the Request class, I came up with this.

app/Http/Requests/ApiRequest.php

<?php

namespace App\Http\Requests;


class ApiRequest extends Request
{
    public function wantsJson()
    {
        return true;
    }
}

Then, in every controller just pass \App\Http\Requests\ApiRequest

public function index(ApiRequest $request)

SimonDepelchin

I know this post is kind of old but I just made a Middleware that replaces the "Accept" header of the request with "application/json". This makes the wantsJson() function return true when used. (This was tested in Laravel 5.2 but I think it works the same in 5.1)

Here's how you implement that :

  1. Create the file app/Http/Middleware/Jsonify.php

    namespace App\Http\Middleware;
    
    use Closure;
    
    class Jsonify
    {
    
        /**
         * Change the Request headers to accept "application/json" first
         * in order to make the wantsJson() function return true
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * 
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $request->headers->set('Accept', 'application/json');
    
            return $next($request);
        }
    }
    
  2. Add the middleware to your $routeMiddleware table of your app/Http/Kernel.php file

    protected $routeMiddleware = [
        'auth'       => \App\Http\Middleware\Authenticate::class,
        'guest'      => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'jsonify'    => \App\Http\Middleware\Jsonify::class
    ];
    
  3. Finally use it in your routes.php as you would with any middleware. In my case it looks like this :

    Route::group(['prefix' => 'api/v1', 'middleware' => ['jsonify']], function() {
        // Routes
    });
    

if your request has either X-Request-With: XMLHttpRequest header or accept content type as application/json FormRequest will automatically return a json response containing the errors with a status of 422.

i just override the failedValidation function

protected function failedValidation(Validator $validator)
{
        if ($this->wantsJson()) {
            // flatten all the message
            $collection  = collect($validator->errors())->flatten()->values()->all();
            throw new HttpResponseException(Response::error('Validation Error', $collection));
        }

        parent::failedValidation($validator);
}

So output sample:

{
    "error": true,
    "message": "Validation Error",
    "reference": [
        "The device id field is required.",
        "The os version field is required.",
        "The apps version field is required."
    ],
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!