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?
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.
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.
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 () {
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With