How to Set a Custom HTTP Response Code in Laravel

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

When building web applications with Laravel, you might encounter situations where you need to return a specific HTTP status code from your routes or controllers. HTTP status codes are standard response codes given by web application servers on the internet. They help to determine the outcome of an HTTP request, such as whether it was successful, redirected, or resulted in an error. In this tutorial, we will learn how to set custom HTTP response codes in Laravel, an important skill for creating a robust and standard-compliant API or web application.

Prerequisites

  • A basic understanding of PHP and Laravel
  • Laravel Framework Installed (version used in this guide: 9.x)
  • Composer dependency manager
  • A text editor or IDE of your choice

Setting a Custom HTTP Response Code

To set a custom HTTP response code in Laravel, there are various methods you can use depending on your specific requirements. Here are some code examples illustrating different approaches:

Using the response() Helper Function

Laravel provides the response() helper, which makes it effortless to create a response with a custom status code. Here is a simple example:

Route::get('/custom-response', function () {
    return response('Content', 418);
});

In this example, we define a route that points to a closure. It uses the response() helper function to return some content (‘Content’) with the 418 HTTP status code, which amusingly denotes ‘I’m a teapot.’

Using the Response Facade

Another way to specify a custom status code is through the Response facade. Below is an example of how to send a 404 status code using this approach:

use Illuminate\Support\Facades\Response;

Route::get('/not-found', function () {
    return Response::make('Not Found', 404);
});

The Response::make() method creates a response with the given content and status code. This example returns a ‘Not Found’ message with a 404 status code indicating that the requested resource was not found.

Setting Headers Along with a Custom Status Code

Sometimes you might need to set custom headers along with your response. You can do this using the response() helper function as well:

Route::get('/with-headers', function () {
    return response('Content', 202)
                 ->header('Content-Type', 'text/plain')
                 ->header('Custom-Header', 'HeaderValue');
});

In this code snippet, we return content with a 202 ‘Accepted’ status code and add custom headers to the response.

Creating JsonResponse with a Custom Status Code

When dealing with API development, you will often need to return JSON responses. Laravel provides an easy way to do so with the JsonResponse class:

use Illuminate\Http\JsonResponse;

Route::get('/json-response', function () {
    return new JsonResponse(['message' => 'Hello World'], 200);
});

You can also use the response() helper function to return a JSON response with a custom status code:

Route::get('/json-shortcut', function () {
    return response()->json(['message' => 'Hello World'], 200);
});

Both JsonResponse constructor and response()->json() take data as the first parameter and the status code as the second.

Custom HTTP Responses with Exceptions

Laravel allows you to handle exceptions in a centralized location: the exception handler. You may want to return a custom status code when an exception occurs. Here’s how:

use Symfony\Component\HttpKernel\Exception\HttpException;

// Inside your controller or other business logic
throw new HttpException(403, 'Forbidden');

This line of code will produce a response with a 403 status code and ‘Forbidden’ message.

Error Responses and HTTP Exceptions

Laravel provides several built-in exceptions that correspond to different HTTP status codes, such as NotFoundHttpException or MethodNotAllowedHttpException. You can use these to standardize your API’s error responses quickly.

use Illuminate\Database\Eloquent\ModelNotFoundException;

Route::get('/user/{id}', function ($id) {
    // Assuming you have a User model and you are looking for a specific user by id
    $user = User::findOrFail($id);
    // If the user is not found, a ModelNotFoundException will be thrown
    // This can be caught in your app/Exceptions/Handler.php file where you
    // can return a custom JSON response with the required status code:

    // ...

    // Inside the render() method of App\Exceptions\Handler class
    if ($exception instanceof ModelNotFoundException) {
        return response()->json(['message' => 'User not found'], 404);
    }

    // Continue with the normal exception handling
    return parent::render($request, $exception);
});

In this code, we are using Laravel’s findOrFail method, which automatically throws a ModelNotFoundException if the user is not found. You can catch this exception in your exception handler and return a response with a custom status code.

Conclusion

Setting custom HTTP status codes in Laravel is straightforward and provides you with the flexibility to communicate the status of HTTP requests effectively. Whether you’re working with web routes and need to display error messages to users or you’re developing an API that requires a clear status code communication scheme, understanding how to control these responses is an essential part of modern web development. With the examples and methods explained in this guide, you’re now ready to implement your own custom HTTP response codes in your Laravel applications.