Tired of custom middleware to force JSON responses for API exceptions in Laravel? Laravel 11 streamlines this process. This approach eliminates the need for middleware like this:
class ForceJsonResponse { public function handle(Request $request, Closure $next) { $request->headers->set('Accept', 'application/json'); return $next($request); } }
Now, you can achieve the same result directly within your application configuration:
// bootstrap/app.php return Application::configure(basePath: dirname(__DIR__)) //... ->withExceptions(function (Exceptions $exceptions) { $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { return $request->is('api/*'); }); })->create();
This concise code, leveraging the shouldRenderJsonWhen()
method, ensures all exceptions within API routes (api/*
) are rendered as JSON, regardless of the Accept
header. Remember, you'll still need to handle non-error responses to guarantee they also return JSON.
This elegant solution is directly from the Laravel documentation, a valuable resource offering further guidance on exception throttling, error response customization, and more.
The above is the detailed content of Always Render API Exceptions as JSON in Laravel. For more information, please follow other related articles on the PHP Chinese website!