An HTTP response contains a status code that indicates whether a request sent by the client has been successfully processed. This tutorial provides 2 methods how to set HTTP response status code in Symfony 7 application.
Method 1 - constructor
The HTTP status code can be provided as the second argument of the constructor when creating an instance of the Response
class.
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
#[Route('/')]
public function index(): Response
{
return new Response('', 201);
}
}
Method 2 - 'setStatusCode' method
The setStatusCode
method can be used to set the HTTP status code if an instance of the Response
class is already created.
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
#[Route('/')]
public function index(): Response
{
$response = new Response();
$response->setStatusCode(201);
return $response;
}
}
Leave a Comment
Cancel reply