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

后端 未结 6 2061
面向向阳花
面向向阳花 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:25

    Laravel Middleware is Extremely useful in this use case.

    1. Make JsonResponseMiddleware middleware.

    php artisan make:middleware JsonResponseMiddleware

    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\JsonResponse;
    use Illuminate\Http\Request;
    use Illuminate\Routing\ResponseFactory;
    
    class JsonResponseMiddleware
    {
        /**
         * @var ResponseFactory
         */
        protected $responseFactory;
    
        /**
         * JsonResponseMiddleware constructor.
         */
        public function __construct(ResponseFactory $responseFactory)
        {
            $this->responseFactory = $responseFactory;
        }
    
        /**
         * Handle an incoming request.
         *
         * @param Request $request
         * @param Closure $next
         * @return mixed
         */
        public function handle(Request $request, Closure $next)
        {
            // First, set the header so any other middleware knows we're
            // dealing with a should-be JSON response.
            $request->headers->set('Accept', 'application/json');
    
            // Get the response
            $response = $next($request);
    
            // If the response is not strictly a JsonResponse, we make it
            if (!$response instanceof JsonResponse) {
                $response = $this->responseFactory->json(
                    $response->content(),
                    $response->status(),
                    $response->headers->all()
                );
            }
    
            return $response;
        }
    }
    

    2. Registor middleware in App\Http\Kernel.php

    protected $middlewareGroups = [
    
            'api' => [
                ...
                ....
                /// Force to Json response (Our created Middleware)
                \App\Http\Middleware\JsonResponseMiddleware::class,
            ],
    
    
            'web' => [
                ...
                ....
                /// Add Here as well if we want to force response in web routes too.
            ],
    ]
    

    Now we will receive every response in JSON only.

    NOTE: Exceptions Too

提交回复
热议问题