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.

Chin Leung
  • 14,621
  • 3
  • 34
  • 58
JacopoStanchi
  • 1,962
  • 5
  • 33
  • 61

2 Answers2

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"
]
Chin Leung
  • 14,621
  • 3
  • 34
  • 58
  • 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 Jun 12 '18 at 16:06
  • 1
    @JacopoStanchi Yes it is normalized for URL. You can do the way you suggested but it will pass a string into an array. – Chin Leung Jun 12 '18 at 16:15
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]
});
Dexter Bengil
  • 5,995
  • 6
  • 35
  • 54