Laravel - 如何从控制器设置 HTTP 响应状态代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48877039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - How to set HTTP response status code from Controller
提问by climbd
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.
我是 laravel 的新手,我成功地将用户从控制器引导到适当的视图,但在某些情况下,我想设置一个 http 状态代码,但200
无论我发送什么,它总是返回响应代码。
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.
如果我在路由中使用相同的代码,它将返回正确的 http 状态代码,正如我在命令行中使用 curl -I 调用页面时看到的那样。
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?
我究竟做错了什么?
回答by Kenny Horna
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.
注意setStatusCode($integer)
方法。
Alternative
选择
You could set an additional header when returning the view to specify additional data, as the documentationstates:
您可以在返回视图以指定其他数据时设置附加标题,如文档所述:
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');
将标题附加到响应
请记住,大多数响应方法都是可链接的,从而可以流畅地构建响应实例。例如,您可以使用 header 方法在将响应发送回用户之前向响应添加一系列标头:
return response($content) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value');