简体   繁体   中英

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?

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM