0

How to pass multiple values of a single HTTP request parameter, and retrieve them in the controller?

Whether it be a repeated parameter like so:

http://example.com/users?q=1&q=2

or multiple values in a row like that:

http://example.com/users?q=1,2

Thank you for your help.

10
  • Laravel help page / user guide? Commented Jun 12, 2018 at 14:59
  • See by yourself, I saw nothing about multiple values parameters laravel.com/docs/5.6/requests#retrieving-input Commented Jun 12, 2018 at 15:00
  • Just grab them from the $_GET array (in the controller) provided that your route is example.com/users Commented Jun 12, 2018 at 15:01
  • I'm not sure about the first one, but the second approach gives you a string that you can split in your controller Commented Jun 12, 2018 at 15:01
  • $input = $request->all(); and then foreach? Commented Jun 12, 2018 at 15:06

2 Answers 2

4

You can pass an array to the request like this:

http://example.com/users?q[]=1&q[]=2

The [] will pass the parameter as an array. Therefore, when you retrieve the q from the request:

dd(request('q'));

It will give you the following:

array:2 [▼
  0 => "1"
  1 => "2"
]
Sign up to request clarification or add additional context in comments.

2 Comments

Are the [] characters 'normalized' for URL, like ? and & for example or is this just a shorthand only available for Laravel (and not for Spring, etc.)? Can I do ?q[]=1,2?
@JacopoStanchi Yes it is normalized for URL. You can do the way you suggested but it will pass a string into an array.
3

Just like when you pass an html input with a value of array, you can pass it with []. e.g. /users?q[]=1&q[]=2

Route::get('users', function (Illuminate\Http\Request $request) {
    // when you dump the q parameter, you'll get:
    dd($request->q);
    // q = [1, 2]
});

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.