Reputation: 415
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?
Upvotes: 8
Views: 22445
Reputation: 14271
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.
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');
Upvotes: 25