如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:05:26  来源:igfitidea点击:

How do I get raw form data in laravel?

phphttplaravelput

提问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://inputstream can only be read once. This means that you need to get the data from the framework. You can do this by accessing the getContentmethod on the Requestinstance, 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\Requestextends Symfony\Component\HttpFoundation\Request, and getContentis defined here: http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/Request.html#method_getContent

由于Illuminate\Requestextends 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 getContentas 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