2016-09-26 21 views
-1

我有一個表單,用戶可以輸入開始位置,提交時他將轉到以此位置爲中心的地圖。他也可以跳過這一步並直接轉到地圖。 (這是跳過整個背景故事的簡化版本)Laravel顯示參數名稱而不是值(在路由中使用可選參數時)

這是第一段代碼,當用戶使用表單時,它將從表單的起始位置並重定向到地圖:(不介意規劃變量,它永遠是這種情況的目的,「自己」)

Route::post('InitiateUserTrip', ['as' => 'InitiateUserTrip', function(WelcomeFormRequest $request) 
{ 
    if (Input::get('planning') == 'own') { 
     return Redirect::route('Map',array('startLocation', Input::get('startLocation'))); 
    } else { 
     return view('welcome'); 
    } 
} ]); 

這是地圖的路線時,startLocation是可選如上所述。 (API密鑰將是我的個人API密鑰。)我在這裏看到的情況是,調試欄顯示'startLocation'而不是參數的值。 (名稱代替值)

Route::get('Map/{startLocation?}', ['as' => 'Map', function($startLocation = null) 
{ 
    $map = new Map('API KEY',$startLocation,'GMainMap');  
    $googleMap = $map->getMap(); 
    $node = new Node(); 
    $node->loadBySelection('ALL'); 
    $nodes = $node->getNodes(); 
    \Debugbar::info("Map: " . $startLocation); 
    return View::make('map')->with('map', $googleMap) 
          ->with('nodes',$nodes) 
          ->with('startLocation',$startLocation); 
}]); 

我開始玩這個URL來看看發生了什麼。 假設用戶輸入 '邁阿密' 作爲startLocation這將導致以下網址:

http://laravel.dev/Map/startLocation?Miami => Debugbar會顯示 'startLocation'

當我修改URL自己 http://laravel.dev/Map/Miami => Debugbar會顯示「邁阿密'

這不僅僅是顯示錯誤內容的Debugbar。我嘗試基於此變量進行地理編碼,並且因爲它將內容視爲「startLocation」而失敗。

我可以通過創建兩個路徑來解決這個問題,其中一個有一個沒有參數,但我想我只是缺少一些明顯的東西。

+0

爲什麼你使用「?」在路由中,刪除這個 –

+1

@ImtiazPabel'?'表示路由參數是可選的並且完全有效。 – Jonathon

+0

請記住,路由參數與GET參數不同(來自URL中'?'後面的查詢字符串)。 '/ Map/Miami'會正確地返回'''''作爲'$ startLocation',與'/ Map/startloaction?邁阿密'正確*顯示''startLocation''的startLocation'相同。當你真的應該選擇一個參數時,你正試圖使用​​URL和'GET'參數。 –

回答

0

你有你的路線調用中的錯誤

Redirect::route('Map',array('startLocation', Input::get('startLocation'))); 

應該是這樣的:

Redirect::route('Map',array(Input::get('startLocation'))); 

您不需要在路由調用中指定鍵,該數組將與給定路由中的參數配對,這取決於它們在數組中的位置,例如。數組中的第一項到路由中的第一個參數,數組中的第二項到路由中的第二個參數等。

+1

只是爲了讓它更清楚一點,使用鍵是可以的,但它嘗試的方式仍然是錯誤的。 'array('startLocation'=> Input :: get('startLocation'))' – user3158900

+0

我原本想要提供這個建議,但我的解決方案需要更少的代碼:)當然,兩者都是正確的。 –

+0

謝謝,解決了我的問題! – DiscoFever

0

您的路線按預期工作。請記住,{startLocation?}不是URL的一部分,但佔位符將由替換爲的實際參數值。

因此,您的Route :: get('Map/{startLocation?}',...);路線說,startLocation參數值是什麼後立即地圖/。所以如果你去Map/startLocation?邁阿密,startLocation字符串被視爲參數的值。 ?

同時服務於/地圖/地圖/ startLocation邁阿密網址,最簡單的方法是定義2條路線:

Route::get('Map', ...); 
Route::get('Map/startLocation?{startLocation}', ...);