Laravel - Return json along with http status code
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
In today's modern web development world, we often need to tailor our API responses according to various scenarios. For instance, you may want to provide an HTTP status code other than the default 200 (OK) along with your JSON response. In this comprehensive blog post, we will guide you through how to modify the status code in Laravel and even add custom messages alongside your JSON response.
Utilizing Laravel's Response Object
To return a JSON response, Laravel provides an elegant way using its Response object. A simple yet effective example is:php
return Response::json([
'hello' => $value
]);Setting Custom Status Codes
Apart from the default response, there are times when you might want to modify both the JSON content and the HTTP status code to convey specific information. To achieve this, Laravel allows you to set a custom status code within your Response object. Here's how that looks:php
return Response::json([
'hello' => $value
], 201) // Set the status code to 201Adding Custom Messages
In some scenarios, you might also need to include custom messages alongside your JSON response and HTTP status code. Laravel allows you to do this via the withHeader() method of the Response object. Here's an example:php
return Response::json([
'hello' => $value
], 201) // Set the status code to 201
->withHeader('X-Custom-Message', 'Your file was successfully uploaded') // Add a custom message header