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 Response::json($data);
In other words I want every response to be JSON. Is there a good way to do that?
Update: The response must be JSON even on exceptions like not found exception.
To return
JSON
in the controller justreturn $data;
For a
JSON
response on errors, go toapp\Exceptions\Handler.php
file and look at therender
method.You should be able to re-write it to look something like this:
However you will have to decide what to do with
$e
, because it needs to be anarray
. 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.I know this has been answered but these are not good solutions because they change the status code in unpredictable ways. the best solution is to either add the appropriate headers so that Laravel returns JSON (I think its
Accept: application/json
), or follow this great tutorial to just always tell Laravel to return JSON: https://hackernoon.com/always-return-json-with-laravel-api-870c46c5efb2You could probably also do this through middleware as well if you wanted to be more selective or accommodate a more complex solution.