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

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article