How do you force a JSON response on every response in Laravel?

后端 未结 6 2068
面向向阳花
面向向阳花 2021-02-13 14:31

I\'m trying to build a REST api using Laravel Framework, I want a way to force the API to always responed with JSON not by doing this manulaly like:

return Respo         


        
6条回答
  •  [愿得一人]
    2021-02-13 15:26

    Create a middleware as suggested by Alexander Lichter that sets the Accept header on every request:

    headers->set('Accept', 'application/json');
    
            return $next($request);
        }
    }
    

    Add it to $routeMiddleware in the app/Http/Kernel.php file:

    protected $routeMiddleware = [
        (...)
        'json.response' => \App\Http\Middleware\ForceJsonResponse::class,
    ];
    

    You can now wrap all routes that should return JSON:

    Route::group(['middleware' => ['json.response']], function () { ... });
    

    Edit: For Laravel 6.9+

    Give the json.response middleware priority over other middlewares - to handle cases where the request is terminated by other middlewares (such as the Authorize middleware) before you get to set the Accept header.

    To do this - override the constructor of you App\Http\Kernel class (app/Http/Kernel.php) with:

        public function __construct( Application $app, Router $router ) {
            parent::__construct( $app, $router );
            $this->prependToMiddlewarePriority(\App\Http\Middleware\ForceJsonResponse::class);
        }
    

提交回复
热议问题