将嵌套的参数数组传递给 Laravel 请求对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33205082/
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
pass a nested array of params to laravel request object
提问by Growler
I am trying to pass a params object with two attributes,
我正在尝试传递一个具有两个属性的 params 对象,
- an ID
- an array
- 身
- 数组
to Laravel and access the properties through the $request
object. I am getting the error shown below. How can I accomplish this?
到 Laravel 并通过$request
对象访问属性。我收到如下所示的错误。我怎样才能做到这一点?
Angular:
角度:
return $http({
method: 'GET',
url: url + 'questions/check',
cache: true,
params: {
id: params.question_id, // 1
choices: params.answer_choices // [3, 2]
}
});
Laravel:
拉拉维尔:
$input = $request->all();
return $input; //output: {choices: "2", id: "1"}
return $input['choices']; //output: 2
Clearly, the nested choices
array (which should be [3, 2]
) is not getting passed through here.
显然,嵌套choices
数组(应该是[3, 2]
)没有通过这里。
I've also tried following laravel docs, which state:
我也试过关注laravel docs,其中指出:
When working on forms with "array" inputs, you may use dot notation to access the arrays:
$input = Request::input('products.0.name');
在处理具有“数组”输入的表单时,您可以使用点表示法来访问数组:
$input = Request::input('products.0.name');
I tried:
我试过:
$input = $request->input('choices.1'); //should get `2`
return $input;
Which returns nothing.
什么都不返回。
EDIT: I can tell the choices array is being sent with both values 3 and 2, but am not sure how to get them from the Laravel Request object:
编辑:我可以告诉选择数组正在发送值 3 和 2,但我不确定如何从 Laravel 请求对象中获取它们:
Request URI: GET /api/questions/check?choices=3&choices=2&id=1 HTTP/1.1
请求 URI: GET /api/questions/check?choices=3&choices=2&id=1 HTTP/1.1
Response from:
回应来自:
$input = $request->all();
return $input;
回答by David Boskovic
You need to set the key in the same way you would build a url-formatted form request.
您需要以与构建 url 格式的表单请求相同的方式设置密钥。
return $http({
method: 'GET',
url: url + 'questions/check',
cache: true,
params: {
id: params.question_id, // 1
"choices[]": params.answer_choices // [3, 2]
}
});
The server will then receive your request like questions/check?id=1&choices[]=3&choices[]=2
然后服务器将收到您的请求,例如 questions/check?id=1&choices[]=3&choices[]=2
The $http
service flattens your params into a query string. For some reason it's not smart enough to add the brackets which are required in order for the server to read your query string as an array.
该$http
服务将您的参数扁平化为查询字符串。出于某种原因,添加括号是为了让服务器将您的查询字符串作为数组读取所需的括号不够聪明。