【问题标题】:pass a nested array of params to laravel request object将嵌套的参数数组传递给 laravel 请求对象
【发布时间】:2016-01-17 05:58:46
【问题描述】:

我正在尝试传递具有两个属性的 params 对象,

  • ID
  • 一个数组

到 Laravel 并通过 $request 对象访问属性。我收到如下所示的错误。我怎样才能做到这一点?

角度:

            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

显然,嵌套的choices 数组(应该是[3, 2])没有通过这里。

我也试过关注laravel docs,哪个状态:

在处理带有“数组”输入的表单时,您可以使用点表示法 访问数组:

$input = Request::input('products.0.name');

我试过了:

    $input = $request->input('choices.1'); //should get `2`

    return $input;

什么都不返回。


编辑:我可以告诉选择数组正在发送值 3 和 2,但我不确定如何从 Laravel 请求对象中获取它们:

请求 URI:GET /api/questions/check?choices=3&choices=2&id=1 HTTP/1.1

回复来自:

    $input = $request->all();

    return $input;

【问题讨论】:

  • mm 尝试在参数 [{}] 上添加 [],然后访问 input[0]['choices']
  • @melvnberd 我看不出这有什么帮助。此外,$http AJAX 调用需要发送一个对象,而不是一个数组
  • 您在浏览器开发工具网络的 url 中看到了什么?
  • @charlietfl 请见上文

标签: php arrays angularjs laravel laravel-5


【解决方案1】:

您需要以与构建 url 格式的表单请求相同的方式设置密钥。

return $http({
    method: 'GET',
    url: url + 'questions/check',
    cache: true,
    params: {
        id: params.question_id, // 1
        "choices[]": params.answer_choices // [3, 2]
    }
});

然后服务器将收到您的请求,例如questions/check?id=1&choices[]=3&choices[]=2

$http 服务将您的参数扁平化为查询字符串。由于某种原因,添加括号以使服务器将您的查询字符串作为数组读取是不够聪明的。

【讨论】:

    猜你喜欢
    • 2016-04-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2016-08-06
    相关资源
    最近更新 更多