user3871
user3871

Reputation: 12718

pass a nested array of params to laravel request object

I am trying to pass a params object with two attributes,

to Laravel and access the properties through the $request object. I am getting the error shown below. How can I accomplish this?

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.

I've also tried following laravel docs, which state:

When working on forms with "array" inputs, you may use dot notation to access the arrays:

$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:

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

Response from:

    $input = $request->all();

    return $input;

enter image description here

Upvotes: 1

Views: 10038

Answers (1)

David Boskovic
David Boskovic

Reputation: 1519

You need to set the key in the same way you would build a url-formatted form request.

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

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.

Upvotes: 3

Related Questions