1

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

  • 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?

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

4
  • mm try adding [] on params: [{}], then access input[0]['choices'] Commented Oct 19, 2015 at 1:11
  • @melvnberd I don't see how this helps. Also, the $http AJAX call needs to send an object, not an array Commented Oct 19, 2015 at 1:23
  • what do you see in the url in browser dev tools network? Commented Oct 19, 2015 at 1:25
  • @charlietfl see above please Commented Oct 19, 2015 at 1:29

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.