2 Methods to Set HTTP Response Status Code in Laravel 9

2 Methods to Set HTTP Response Status Code in Laravel 9

HTTP response status code allows determining whether a request sent by the client has been successfully processed. This tutorial shows 2 methods how to set HTTP response status code in Laravel 9 application.

Method 1 - constructor

We can provide the HTTP status code as the second argument of the constructor when creating an instance of the Response class.

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;

class TestController extends Controller
{
    public function index(): Response
    {
        return new Response('', 201);
    }
}

Method 2 - 'setStatusCode' method

A Response class extends Symfony\Component\HttpFoundation\Response class, which provides various methods to build HTTP responses. We can use the setStatusCode method to set the HTTP status code if an instance of the Response class is already created.

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;

class TestController extends Controller
{
    public function index(): Response
    {
        $response = new Response();
        $response->setStatusCode(201);

        return $response;
    }
}

The 1 Comment Found

Leave a Comment

Cancel reply

Your email address will not be published.