Force JSON Response For API Requests

If you have built an API and it encounters an error when the request does not contain "Accept: application/JSON " HTTP Header then the error will be returned as HTML or redirect response on API routes, so for avoid it we can force all API responses to JSON.

The first step is creating middleware by running this command:

php artisan make:middleware ForceJsonResponse

Write this code on the handle function in App/Http/Middleware/ForceJsonResponse.php file:

public function handle($request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}

Second, register the created middleware in app/Http/Kernel.php file:

protected $middlewareGroups = [
'api' => [
\App\Http\Middleware\ForceJsonResponse::class,
],
];

Tip given by ferasbbm

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 55 courses (987 lessons, total 46 h 42 min)
  • 77 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord