Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Lumen Ensure JSON response

Tags:

I am new to Laravel and to Lumen. I want to ensure I am always getting only a JSON object as output. How can I do this in Lumen?

I can get a JSON response using response()->json($response);. But when an error happens, API giving me text/html errors. But I want only application/json responses.

Thanks in advance.

like image 931
John Fonseka Avatar asked May 18 '16 10:05

John Fonseka


1 Answers

You'll need to adjust your exception handler (app/Exceptions/Handler.php) to return the response you want.

This is a very basic example of what can be done.

public function render($request, Exception $e) {     $rendered = parent::render($request, $e);      return response()->json([         'error' => [             'code' => $rendered->getStatusCode(),             'message' => $e->getMessage(),         ]     ], $rendered->getStatusCode()); } 
like image 193
Wader Avatar answered Oct 14 '22 01:10

Wader