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

Stefan Izdrail

Founder & Senior Architect · 2026-06-29

Laravel Company
Title: Enforcing JSON Responses in Laravel for Every Request Body: When building a RESTful API using the Laravel framework, you may want all responses to be in JSON format regardless of the endpoint or request. In this blog post, we will discuss how to achieve that goal while still maintaining compatibility with existing code and keeping your application's structure organized. We’ll also briefly explore the importance of JSON-based APIs in Laravel development. Firstly, let's understand why you might want all responses to be JSON in Laravel: JSON (JavaScript Object Notation) is a lightweight data interchange format that makes it easy to transfer data between different systems. It has become the standard for web application development and API communication thanks to its simplicity and broad adoption across platforms. To enforce every response to return as JSON, you can modify your application's global configuration file located in app/config/app.php. Find the 'response' key within the 'aliases' array: ```php // app/config/app.php 'aliases' => [ // ... 'Response' => Illuminate\Support\Facades\Response::class, ], ``` Replace it with a custom alias for your own response class that extends the Laravel Response facade: ```php 'Response' => App\MyCustomJsonResponse::class, ``` Now create a new file called "MyCustomJsonResponse.php" within your project's "App/Http/Responses" directory and define the class as follows: ```php 'application/json']); } } ``` This class extends the Laravel Response class and allows us to pass a JSON response as its first parameter. We also set the content type to 'application/json' for every response. With this new custom response class in place, you can use it by calling: ```php return MyCustomJsonResponse::make($data); ``` This will force any response to be JSON regardless of the original code that might still return HTML or other format. However, please note that this solution might not work for exception responses due to Laravel's default handling of exceptions. In such cases, you may need to create a custom exception handler and provide appropriate response classes for each type of exception to ensure consistent JSON output. In conclusion, enforcing JSON as the only format for all requests in your Laravel application can simplify your API development and streamline communication between different systems. By creating a custom response class and modifying the global configuration file, you can achieve this goal while still maintaining the flexibility of Laravel's powerful framework.