Hobby99
Hobby99

Reputation: 703

Array that was sent as parameter turns into string with only first value of original array

I am sending an array from method 'filterResults' to method 'home' via redirect. The array does go through because the URI changes to www.site.com/country/area/city/category.

But when I print the array inside method 'home' it is not an array anymore but instead it is a string with only the first value (country) of the original array. Why is this the case? Where are the other values? and why is it now a string instead of an array?

Thanks for your help!

Route:

Route::any('home/{s1?}/{s2?}/{s3?}/{s4?}', array(
    'as' => 'home',
    'uses' => 'HomeController@home'
));

Controller Method 'filterResults':

public function filterResults() {
    $filter = array('country' => $country, 'area' => $area, 'city' =>  $city, 'category' =>  $category);
    return Redirect::route('home', $filter);
}

Controller Method 'Home':

public function home($filter = array()) {
    print_r($filter);  //result is a string with the value for country
}

Upvotes: 0

Views: 47

Answers (2)

Sher Afgan
Sher Afgan

Reputation: 1234

You need to define them to get the parameters for example

public function home($param1 = null, $param2 = null, $param3 = null, $param4 = null) {

}

It creates a url because Laravel is smart enough to do that according to the documentation. See array section in route parameters.

Upvotes: 1

Chelsea Urquhart
Chelsea Urquhart

Reputation: 1428

That's not really how Laravel routing works. When you pass it an array, it is expecting an array of arguments.

So your home method will actually receive 4 arguments (the elements of the array).

It makes more sense to make the method something like:

public function home($country = null, $area = null, $city = null, $category = null) {
    print_r($country);
    print_r($area);
    print_r($city);
    print_r($category);
}

Keep in mind that when you're at /country/area/city/category, Laravel has absolutely no idea that you want those in an array. An alternative if you really have to have it in an array would be to remove the arguments from the home method altogether and use PHPs func_get_args which would give you the arguments in array form. They'd be 0-based indexed though. You could even then pass that through array_map to map 0 to country, 1 to area, 2 to city, and 3 to category, but that is probably a lot of excess work when you can just get at everything via parameters.

Upvotes: 1

Related Questions