Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Quick Tip

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

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.