如何在 Laravel 5 中获取原始 json 请求负载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41452844/
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 to get primitive json request payload in Laravel 5?
提问by zarax
Let say that this is the payload of a request:
假设这是请求的有效载荷:
{name : 'John', age: 42}
You can get all paramters with Request::all()
.
您可以使用Request::all()
.
How do I get request payload correctyly if payload is a primitive type like true
or 42
?
如果有效负载是原始类型(如true
或 ),如何正确获取请求有效负载42
?
Request::getContent()
receives them as strings, I want them to be in correct type as well.
Request::getContent()
将它们作为字符串接收,我也希望它们的类型正确。
回答by Antonio Carlos Ribeiro
You can use json_decode
to decode a raw json payload to an array:
您可以使用json_decode
将原始 json 负载解码为数组:
Route::post('/request', function () {
$payLoad = json_decode(request()->getContent(), true);
dd($payLoad['name']);
});
And you should get
你应该得到
John
Or can use json_decode
to decode your payload from a query parameter or post data:
或者可以用于json_decode
从查询参数或发布数据解码您的有效负载:
Route::get('/primitive', function () {
$payLoad = json_decode(request()->get('payload'));
dd($payLoad);
});
Hitting:
打:
http://app.dev/primitive?payload={%20%22name%22:%20%22John%22,%20%22age%22:%2042,%20%22male%22:%20true%20}
You should get
你应该得到