How do you force a JSON response on every response in Laravel?

How do you force a JSON response on every response in Laravel?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Global JSON Response Strategy in Laravel

Enforcing a uniform JSON response format across an entire application is a standard requirement when building REST APIs. While manually wrapping every return statement with Response::json() works, it quickly becomes unmanageable as the codebase grows. The goal is to ensure that every single HTTP response, including those triggered by exceptions like 404 Not Found or 500 Internal Server Error, adheres to a JSON schema without cluttering controller logic.

Laravel provides a specific configuration mechanism to handle this requirement globally. By defining the default response format in your app/config/app.php (in older versions) or via the application bootstrap process, you can instruct the framework to serialize all responses as JSON by default. This setting ensures that even if a controller returns a plain PHP array, string, or object, Laravel will automatically wrap it in a JSON response with the correct Content-Type header.

To implement this, you need to modify the application's default configuration. In modern Laravel versions, the primary entry point for global settings is the app/config/app.php file (or the config/app.php directory depending on your version). Locate the default_response_format setting within the configuration array. You should set this value to 'json'.

// app/config/app.php or config/app.php
return [
    // ... other config options
    
    'default_response_format' => 'json',
    
    // ... other config options
];

Once this flag is active, the framework intercepts the response generation process. If your controller returns a standard array like ['status' => 'success'], Laravel automatically converts it to {'status': 'success'} with the header Content-Type: application/json. This eliminates the need for explicit return Response::json() calls in your route closures or controller methods, significantly reducing boilerplate code.

However, there is a critical nuance regarding exceptions, as highlighted in the specific requirement that errors must also return JSON. By default, Laravel's exception handler might render HTML error pages (like the classic 500 error page) for uncaught exceptions. To guarantee that exceptions also return JSON, you must customize your App\Exceptions\Handler class.

You can override the report and render methods to ensure consistency. Specifically, modifying the render method allows you to inspect the exception and determine if a response should be rendered as JSON. A common pattern involves checking if the application is in API mode or simply enforcing JSON for all exceptions regardless of context.

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;

class Handler extends \App\Exceptions\Handler
{
    /**
     * Report an exception.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report($e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        // Ensure exceptions always return JSON responses in API mode
        if ($this->isApiRequest() || config('app.response_format', 'json') === 'json') {
            return $this->renderJsonResponse($e);
        }

        return parent::render($request, $e);
    }

    /**
     * Render a JSON response for an exception.
     *
     * @param  Exception  $e
     * @return \Illuminate\Http\JsonResponse
     */
    protected function renderJsonResponse(Exception $e)
    {
        if ($e instanceof AuthorizationException) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        if ($e instanceof ValidationException) {
            return response()->json(['errors' => $e->errors()], 422);
        }

        // Handle other exceptions including 404s and 500s
        if (config('app.response_format', 'json') === 'json') {
             return response()->json(['message' => config('app.debug') ? $e->getMessage() : 'Something went wrong'], 500);
        }

        return parent::render($request, $e);
    }
}

This approach ensures that whether a user requests a resource that doesn't exist or triggers a server error, the response remains consistent with your API contract. It prevents clients from receiving HTML error pages which can break automated parsing scripts.

One potential pitfall is mixing traditional blade views with JSON responses in a single project configured for global JSON. If you have routes serving Blade templates alongside your API endpoints, ensuring that the default_response_format applies only to specific request patterns or disabling it globally while handling exceptions explicitly is crucial. You might need to check the request URI or headers (like Accept: application/json) before enforcing the JSON serialization to avoid breaking view-based routes unintentionally.

By configuring the default response format and customizing the exception handler, you achieve a robust API foundation where every interaction returns structured data, simplifying client-side consumption and ensuring consistent error reporting.

Our network