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

I'm trying to create a REST api using the Laravel Framework, I want to make the API always handle JSON without doing it manulaly like:

return Response::json($data); 

In other words, I want every response to be JSON. Is there a good way to do this?

Update: The response should be JSON even on exceptions like no exception found.

+7
json rest php laravel
source share
3 answers

To return JSON to the controller only return $data;

If JSON to errors, go to the app\Exceptions\Handler.php and look at the render method.

You should be able to overwrite 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 need to decide what to do with $e , because it must be an array . You can also set a status code and an array of headers.

But then, with any error, the JSON response is returned.

Edit: It is also useful to note that you can modify the report method to handle how larvel logs the error. More details here .

+4
source share

I know that they answered this, but these are not very good solutions, because they change the status code in an unpredictable way. the best solution is either to add the appropriate headers so that Laravel returns JSON (I think it is Accept: application/json ), or follow this wonderful guide to just tell Laravel to return JSON: https://hackernoon.com/always-return- json-with-laravel-api-870c46c5efb2

You can also do this through middleware if you want to be more selective or use a more complex solution.

+4
source share

Create a middleware proposed by Alexander Lichter that sets the Accept header for each request:

 <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class ForceJsonResponse { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { $request->headers->set('Accept', 'application/json'); return $next($request); } } 

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

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

Now you can wrap all the routes that should return JSON:

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

All Articles