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

后端 未结 6 2054
面向向阳花
面向向阳花 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条回答
  •  梦毁少年i
    2021-02-13 15:19

    To return JSON in the controller just return $data;

    For a JSON response on errors, go to app\Exceptions\Handler.php file and look at the render method.

    You should be able to re-write it to look something like this:

    public function render($request, Exception $e)
    {
        // turn $e into an array.
        // this is sending status code of 500
        // get headers from $request.
        return response()->json($e, 500);
    }
    

    However you will have to decide what to do with $e, because it needs to be an array. You can also set the status code and header array.

    But then on any error, it will return a JSON response.

    Edit: It's also good to note that you can change the report method to handle how laravel logs the error as well. More info here.

提交回复
热议问题