Home > Blockchain >  How to pass an array to Laravel Route parameter
How to pass an array to Laravel Route parameter

Time:11-05

I wanted to pass a value of typed array to my route parameter, the array could be in any size and a different key-value pairs each time.

Route::get('/example/{array}', ...

So if I have an array like this:

$array = [
  'a' => 'one',
  'b' => 1,
  ...
]

I did this but knew already it ain't gonna work because it looks like I'm passing values to my route parameters named a, b, etc.

route('route.name', $array)

As expected the error says:

... [Missing parameter: array]

So I used the serialize().

route('route.name', serialize($array))

I'm still getting an error, something like:

[Missing parameter: s:1:"a";i:1;s:1:"b";i:2;]

What am I missing ? I also don't understand what the last error says.

CodePudding user response:

PHP have for this the http_build_query function.

$array = [
  'a' => 'one',
  'b' => 1,
];

$query = http_build_query(array('myArray' => $array));

// output: myArray[a]=one&myArray[b]=1

CodePudding user response:

When passing data to a route in Laravel you should make a practice of passing that data in an array like so:

Route:

Route::get('/example/{array}', ...

Calling the named route:

route('route.name', ['array' => serialize($array)])

I don't know if this formatting is required, but it 1. helps you to better format your routes when passing multiple values, and 2, makes your code more readable.

Laravel Routing Documentation

  • Related