在 laravel 中检索 JSON 输入值无效
Retrieving JSON Input Values in laravel not working
我正在使用 Laravel 7.* 并且我想将 post 数据作为 JSON
到 laravel 的路线。
由于 Laravel documantation JSON 文件必须可以使用此代码访问:
$name = $request->input('user.name');
这是 laravel 文档的一部分:
When sending JSON requests to your application, you may access the
JSON data via the input method as long as the Content-Type header of
the request is properly set to application/json.
我正在通过 RestMan 扩展程序在浏览器中对其进行测试,我正在使用 content-type:application/json
Header 发送数据。
但是 $request->input()
总是空的。
我测试了 $request->json();
,这个方法工作正常。为什么 input()
方法不适用于检索 json 数据?
编辑:
这是我在 RestMan 中的请求:
这是我的路线:
Route::post('/get-json-data',function(Request $request){
return $request->input('user.name');
});
请求中的 user
参数是 json 的数组,因此您需要指定索引才能访问各个名称
$request->input('user.0.name');
$request->input('user.1.name');
或者遍历它并得到一个这样的名字数组
$names = [];
foreach($request->user as $user){
$names[] = $user->name;
}
您的原始代码
$request->input('user.name');
如果 user
是一个 json 字段并且 name
是 json 中的一个字段,则
检查将起作用,例如
{
"user":{
"name":"Ford"
}
}
我正在使用 Laravel 7.* 并且我想将 post 数据作为 JSON
到 laravel 的路线。
由于 Laravel documantation JSON 文件必须可以使用此代码访问:
$name = $request->input('user.name');
这是 laravel 文档的一部分:
When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json.
我正在通过 RestMan 扩展程序在浏览器中对其进行测试,我正在使用 content-type:application/json
Header 发送数据。
但是 $request->input()
总是空的。
我测试了 $request->json();
,这个方法工作正常。为什么 input()
方法不适用于检索 json 数据?
编辑:
这是我在 RestMan 中的请求:
这是我的路线:
Route::post('/get-json-data',function(Request $request){
return $request->input('user.name');
});
请求中的 user
参数是 json 的数组,因此您需要指定索引才能访问各个名称
$request->input('user.0.name');
$request->input('user.1.name');
或者遍历它并得到一个这样的名字数组
$names = [];
foreach($request->user as $user){
$names[] = $user->name;
}
您的原始代码
$request->input('user.name');
如果 user
是一个 json 字段并且 name
是 json 中的一个字段,则
检查将起作用,例如
{
"user":{
"name":"Ford"
}
}