Today I was working on an API written in Laravel for a React Native app with another developer.
He was trying to make requests to the Laravel backend and told me he kept receiving a response with a http status code of 302. 3XX http status codes are redirection status codes.
It turned out that he had not set an accept header on the requests to the server that the app was making.
By default if you dont set a requests accept headers they default to
Accept: */*. With those set laravel responds with a
For the purpose of this project every api response needs to return JSON.
We can achieve this really easily by using middleware to overwrite the
Accept headers on the incoming request and setting them to
Create a new middleware class:
php artisan make:middleware RespondWithJsonMiddleware
Now open the new file created in
app/Http/Middleware and change the handle method to look like this:
public function handle($request, Closure $next)
And thats as simple as it gets, now we just need to apply that middleware to a given set of routes.
For my purposes I wanted every request to return JSON so I added this new class to api global middleware group in
If we look at the
app/Providers/RouteServiceProvider.php file we can see that this
api middleware group is applied to all of the routes in ``routes/api.php`:
protected function mapApiRoutes()
If we didn’t want to apply the new middleware to every api route and to a given controller we can do so like this.
First remove the new middleware from the api group
Now add the new middleware item to the
$routeMiddleware array in the same file
protected $routeMiddleware = [
Then use the middleware as you normally would in your routes file
We can also apply this code to a controller using the controller middleware function.
class IndexController extends Controller