How to force FormRequest return json in Laravel 5.1?

前端 未结 5 1639
梦如初夏
梦如初夏 2020-12-05 02:25

I\'m using FormRequest to validate from which is sent in an API call from my smartphone app. So, I want FormRequest alway return json when validation fail.

I saw th

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 03:22

    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
      });
      

提交回复
热议问题