如何在 Laravel 中获取原始表单数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21991906/
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
How do I get raw form data in laravel?
提问by Benubird
I have a script that is trying to send data to my site using HTTP PUT. Normally, I woudl just retrieve it by reading from the input stream with file_get_contents('php://input')
. However, when I try that with laravel, I don't get anything! Why not? How do I read the raw input data?
我有一个脚本试图使用 HTTP PUT 将数据发送到我的站点。通常,我只是通过从输入流中读取它来检索它file_get_contents('php://input')
。但是,当我用 laravel 尝试时,我什么也没得到!为什么不?如何读取原始输入数据?
回答by Benubird
Laravel intercepts all input. If you're using PHP prior to 5.6, the php://input
stream can only be read once. This means that you need to get the data from the framework. You can do this by accessing the getContent
method on the Request
instance, like this:
Laravel 拦截所有输入。如果您使用 5.6 之前的 PHP,则该php://input
流只能读取一次。这意味着您需要从框架中获取数据。您可以通过访问实例getContent
上的方法来执行此操作Request
,如下所示:
$content = Request::getContent(); // Using Request facade
/* or */
$content = $request->getContent(); // If you already have a Request instance
// lying around, from say the controller
Since Illuminate\Request
extends Symfony\Component\HttpFoundation\Request
, and getContent
is defined here: http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/Request.html#method_getContent
由于Illuminate\Request
extends Symfony\Component\HttpFoundation\Request
,并getContent
在此处定义:http: //api.symfony.com/3.0/Symfony/Component/HttpFoundation/Request.html#method_getContent
回答by Mohamed Said
You can also use Request::json($key, $default);
to return the value of a specific key in the json payload.
您还可以使用Request::json($key, $default);
返回 json 有效负载中特定键的值。
回答by Abdurrahman Shofy Adianto
Update for latest Laravel (I'm using laravel 5.8), you may encounter error when using Request::getContent();
because the latest Symfony Request module (which underlie Laravel's Request module) no longer provide getContent
as static method. Instead I use Request::createFromGlobals()->getContent();
.
更新最新的 Laravel(我使用的是 Laravel 5.8),您在使用时可能会遇到错误,Request::getContent();
因为最新的 Symfony 请求模块(Laravel 的请求模块的基础)不再提供getContent
静态方法。相反,我使用Request::createFromGlobals()->getContent();
.
Reference: https://symfony.com/doc/current/components/http_foundation.html#accessing-request-data
参考:https: //symfony.com/doc/current/components/http_foundation.html#accessing-request-data