paint-brush
Always return JSON with Laravel APIby@deleugpn
16,529 reads
16,529 reads

Always return JSON with Laravel API

by Marco Aurélio Deleu1mApril 8th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

I’ve recently started working on some small projects that will only use the backend portion of Laravel. One of the first things we bump into is the Authentication Exception that tries to redirect to <code class="markup--code markup--p-code">/home</code> or <code class="markup--code markup--p-code">/login</code>. That redirection becomes another exception: <code class="markup--code markup--p-code">InvalidArgumentException: Route [login] is not defined.</code>. Here is an extreme simple solution for when you only want to work with API Responses.

Company Mentioned

Mention Thumbnail
featured image - Always return JSON with Laravel API
Marco Aurélio Deleu HackerNoon profile picture

I’ve recently started working on some small projects that will only use the backend portion of Laravel. One of the first things we bump into is the Authentication Exception that tries to redirect to /home or /login. That redirection becomes another exception: InvalidArgumentException: Route [login] is not defined.. Here is an extreme simple solution for when you only want to work with API Responses.

1- Write a new BaseRequest

By extending Laravel Request object, we can override the methods used by the framework that decides whether to give a redirect response or a JSON response to always prefer JSON.

2- Swap the implementation

Inside public/index.php we can find where Laravel builds the Request object. Let’s swap \Illumiate\Http\Request with our new BaseRequest class.



$response = $kernel->handle($request = \App\Http\Requests\BaseRequest::capture());

3- Done!

As simple as this, now any HTTP Request will be treated as it wants application/json as the Response. No more Redirect Exceptions.

Update

Alexander Lichter have a killer one-line middleware to achieve the same result. Check out his solution here.