2013-12-17 34 views
1

我正在尋找將我的路線換成電子商務商店以實現SEO目的。Laravel - 在routes.php中使用'where'來查詢模型

我想創建以下路線:

Route::get('/{country}', ['uses' => 'Store\[email protected]']); 
Route::get('/{category}, ['uses' => 'Store\[email protected]']') 

countrycategory必須是動態的。

我想知道是否有類似以下內容的可能嗎?和實現的最佳途徑。

// Route 1 
Route::get('/{country}', ['uses' => 'Store\[email protected]']) 
    ->where('country', ProductCountry::select('slug')->get()); 

// Route 2 
Route::get('/{category}', ['uses' => 'Store\[email protected]']) 
    ->where('category', ProductCategory::select('slug')->get()); 

例如路線:

/great-britain should be routed via Route 1 
/china   should be routed via Route 1 

/widgets  should fail route 1, but be routed via Route 2 because 
       widgets are not in the product_country table but are in 
       the product_category table 

我知道我可以寫死我的路線有可能的國家:

Route::get('/{country}', ['uses' => 'Store\[email protected]']) 
    ->where('country', 'great-britain|china|japan|south-africa'); 

然而,這是笨拙和tedius。我想從數據庫中獲取國家列表。

+0

肯定會在你的控制器處理不是在你的路線,你會不顧國家傳遞到你的控制器,但隨後的控制器會做你的國家==做xxx其他人做yyy等 – Dave

+0

你可以使用Route :: model()來實現這一點。 – Anam

+0

@Dave - 如果我想限制特定國家可用於控制器,我如何將路線傳遞到該國家?做你的方法,我的路線必須是'Route :: get('country'/ {country})'我不想要的。 – Gravy

回答

0

好的,在查看更新後的問題後,您需要在各自的模型中創建一個方法,以將所有可用的slugs與|字符,所以你會打電話來是這樣的:

Route::get('/{country}', ['uses' => 'Store\[email protected]']) 
    ->where('country', ProductCountry::getSlugs()); 

這幾乎迴歸「大英|中國|日本|南非洲象你的榜樣,但你不會寫。

然而,我強烈建議你給路由多一點,/ country/{country}或/ category/{category},否則它會令人困惑,而URI結構通常是這樣的,這樣用戶可以準確地看到他們在哪裏。

+0

謝謝,我已更新我的問題以提供一些清晰度。 – Gravy

+0

更新了我的答案。 – ollieread

+0

謝謝。我會放棄它。我瞭解你的建議,並在一定程度上同意它。但是,您是否曾經在URL中看到帶有單詞類別或國家/地區的在線商店? – Gravy

0

您需要路由過濾器來實現這一點。

地方下面的代碼filters.phproute.php文件

Route::filter('country', function() 
{ 

    $country = Country::where('slug', Route::input('country'))->first(); 
    if( ! $country) { 
     dd("We do not support this country"); 
      // Redirect::route('home'); 
    } 

}); 

終於路線:

Route::get('country/{country}', array('before' => 'country', 'uses' => 'Store\[email protected]')); 
1

我會做這樣我選擇的國家模型,因爲有以下排量車型+你需要緩存: 更改列表('名稱')到國家名稱列

Route::get('/{country}', ['uses' => 'Store\[email protected]']) 
->where('country', implode('|',ProductCountry::select('slug')->lists('name'))); 

是什麼做的是選擇所有國家的名稱,並返回它們作爲數組這樣

('usa','england','thailand') 

,並使用與內爆「|」膠水返回此:

usa|england|thailand 

所以您的最終路線是這樣的:

Route::get('/{country}', ['uses' => 'Store\[email protected]']) 
->where('country', 'usa|england|thailand'); 
+0

這打破了我的遷移,因爲artisan加載routes.php並且沒有遷移,routes.php中的查詢將失敗。你有這個解決方案嗎? – Ezra

+0

@Ezra爲什麼不改變路線到類別/ {category}? –

+0

我希望我能,但我需要建立的路線必須像這樣工作。我通過允許我將一個閉包傳遞給Route:pattern和Route ::來解決這個問題,它只在laravel調用symfony路由器之前運行此回調。工匠實際上並沒有使用這個回調的路線,只有當路線真的用於我的問題時纔會被調用! – Ezra