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

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

    You can create an After Middleware and change structure of all responses

    Middleware:

    namespace App\Http\Middleware;
    
    use Closure;
    
    class ChangeResponseStructureMiddleware
    {
        public function handle($request, Closure $next)
        {
            $response = $next($request);
    
            $newContent = [
                'data' => $response->getOriginalContent(),
                'context' => [
                    'code' => $response->getStatusCode()
                ]
            ];
    
            return $response->setContent($newContent);
        }
    }
    

    this middleware will force the response content to be like

    {
       "data": "response content of controller",
       "context": {
           "code": 200 // status code
       }
    }
    

提交回复
热议问题