Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - How to set HTTP response status code from Controller

I'm new to laravel and am successfully directing users tothe appropriate views from a controller, but in some instances I want to set an http status code, but it is always returning a response code of 200 no matter what I send.

Here is the code for my test controller function:

public function index()
{
    $data=array();

    return response()->view('layouts.default', $data, 201);
}

If I use the same code within a route, it will return the correct http status code as I see when I call the page with curl -I from the command line.

curl -I http://localhost/

Is there a reason why it doesn't work within a controller, but does within a route call?

I'm sure there is something I'm just misunderstanding as a newbie, but even the following code works in a route but not a controller:

public function index()
{
    abort(404);
}

What am I doing wrong?

like image 976
climbd Avatar asked Feb 20 '18 02:02

climbd


People also ask

How do I return a response with a status code?

You can use http_response_code() to set HTTP response code. If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code. Save this answer.

How can we send response from laravel?

Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response.

What is HTTP response in laravel?

Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response: Route::get('/', function () {


1 Answers

Solution

You could use what is mentioned here. You will need to return a response like this one:

public function index()
{
    $data = ['your', 'data'];

    return response()->view('layouts.default', $data)->setStatusCode(404); 
}   //                                                ^^^^^^^^^^^^^^^^^^^

Notice the setStatusCode($integer) method.

Alternative

You could set an additional header when returning the view to specify additional data, as the documentation states:

Attaching Headers To Responses

Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:

return response($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value')
            ->header('X-Header-Two', 'Header Value');
like image 96
Kenny Horna Avatar answered Oct 11 '22 16:10

Kenny Horna