Laravel Tutorials

Always Render API Exceptions as JSON in Laravel

Published
Always Render API Exceptions as JSON in Laravel image

Have you ever enforced returning JSON on API requests for exceptions using a custom middleware like the following:

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

Laravel 11 gives you a handy way to do this without any extra middleware. I think it's really nice if you are using a web browser to test API routes and always get JSON even without setting the Accept header to application/json or using the above middleware:

// bootstrap/app.php
 
return Application::configure(basePath: dirname(__DIR__))
 
//...
 
->withExceptions(function (Exceptions $exceptions) {
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
if ($request->is('api/*')) {
return true;
}
 
return $request->expectsJson();
});
})->create();

Using the shouldRenderJsonWhen() method, this code ensures that any exceptions thrown during an API request are rendered as JSON. Besides exceptions, it's up to you to ensure non-error responses return JSON.

This tip comes straight from the documentation, which also has some excellent tips on throttling exceptions, customizing error responses, and more!

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Securing Filament plugins with Plumb image

Securing Filament plugins with Plumb

Read article
LayaPHP: Self-Hosted Text Classification for PHP and Laravel image

LayaPHP: Self-Hosted Text Classification for PHP and Laravel

Read article
WhenMounted and BigInt Props in Inertia.js v3.8 image

WhenMounted and BigInt Props in Inertia.js v3.8

Read article
Postcodes for Laravel: GB Postcode Lookup and Geography Data image

Postcodes for Laravel: GB Postcode Lookup and Geography Data

Read article
Laravel 14 Adds a defaults() Method to Eloquent Models image

Laravel 14 Adds a defaults() Method to Eloquent Models

Read article
Laravel AI SDK and Laravel MCP Security Fixes: Update Now image

Laravel AI SDK and Laravel MCP Security Fixes: Update Now

Read article