Search code examples
phpjsonapilaravellumen

Laravel Lumen Ensure JSON response


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.


Solution

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