2015-02-07 32 views
2

我有這樣的路線:Laravel - 重定向路由具有可選參數

Route::get('search/{state?}/{city?}/{brand?}/{model?}', array('as'=>'search-cars'), function($a=false, $b=false, $c=false, $d=false) { 
    // Do stuff 
} 

如何從我的控制器將參數傳遞給上面的路線?我已經試過:

public function postHomeSearch() { 
    $state= (Input::get('state')) ? Input::get('state') : null; 
    $city = (Input::get('city')) ? Input::get('city') : null; 
    $brand= (Input::get('brand')) ? Input::get('brand') : null; 
    $model= (Input::get('model')) ? Input::get('model') : null; 

    $data = array(
     'state' => $state, 
     'city' => $city, 
     'brand' => $make, 
     'model' => $model, 
    ); 

    return Redirect::route('search-cars',$data); // <---- HERE 
} 

請注意,如果他們不選擇

+0

你的代碼只是似乎不錯。如果數組爲null,是否嘗試過不在數組中包含參數?此外,匹配功能簽名上的參數名稱。 – facundofarias 2015-02-07 19:23:04

+0

這個解決方案有什麼不起作用? – lukasgeiter 2015-02-07 19:25:46

+0

@facundofarias和lukasgeiter ...我在調用postHomeSearch()時得到這個URL ** http:// localhost/laravel/App/public/search /// California ///全部** - 注意三重**/// ** – Daniel 2015-02-07 19:28:38

回答

2

這看起來對我來說,這個問題的null值一些參數可以爲空。您可以刪除使用array_filter那些,然後將數據傳遞給重定向功能沒有關聯數組,但只是作爲值(所以他們會爲了和沒有通過參數名稱來解決)

$data = Input::only('state', 'city', 'brand', 'model'); 
$data = array_filter($data); // remove falsy values 
$data = array_values($data); // remove keys 
return Redirect::route('search-cars', $data); 
+0

謝謝你完美的作品:) – Daniel 2015-02-07 20:18:58

+0

很高興聽到這一點。我還建議你將路由中的參數名改爲'{a?}/{b?}'。這會讓事情變得更清楚,「{state?}」實際上不必是狀態...... – lukasgeiter 2015-02-07 20:20:53

+0

@lukaseiter會做謝謝! – Daniel 2015-02-07 20:29:43