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.
<?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.
<?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
Even shorter you can do this too
Leave a Comment
Cancel reply