Laravel Lumen Ensure JSON response

John Fonseka picture John Fonseka · May 18, 2016 · Viewed 16.7k times · Source

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.

Answer

Wader picture Wader · May 18, 2016

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());
}