我希望扁平我的搜索引擎优化目的电商商店我的路线。
我想创建以下路由:
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry']);
Route::get('/{category}, ['uses' => 'Store\ProductController@browseCategory']')country和category必须是动态的。
我想知道下面这样的事情是否可能发生?最好的实现方式。
// Route 1
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry'])
->where('country', ProductCountry::select('slug')->get());
// Route 2
Route::get('/{category}', ['uses' => 'Store\ProductController@browseCategory'])
->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\ProductController@browse'])
->where('country', 'great-britain|china|japan|south-africa');然而,这是笨拙和乏味的。我想从数据库中得到国家的名单。
发布于 2013-12-17 20:41:41
我将这样做,我选择国家/地区模型,因为您需要缓存的名称较少:将列表(‘models+’)更改为country name列
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry'])
->where('country', implode('|',ProductCountry::select('slug')->lists('name')));它所做的是选择所有国家/地区的名称,并将它们作为数组返回,如下所示
('usa','england','thailand') 并使用内爆与'|‘作为胶水返回以下内容:
usa|england|thailand所以你的最终路线是这样的:
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry'])
->where('country', 'usa|england|thailand');发布于 2013-12-17 19:09:18
好的,在查看完更新后的问题之后,您需要在各自的模型中创建一个方法,以便将所有可用的slug与|字符连接起来,这样您就可以调用如下代码:
Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry'])
->where('country', ProductCountry::getSlugs());这会像你的例子中一样返回‘great-britain|china|日本|south-south’,只是你不需要写出来。
但是,我强烈建议您为路由提供更多的内容,/country/{country}或/category/{category},否则会令人困惑,并且URI结构通常是这样的,这样用户就可以准确地看到他们所在的位置。
发布于 2013-12-17 19:44:22
您需要路由过滤器来实现这一点。
将以下代码放入filters.php或route.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\ProductController@browseCountry'));https://stackoverflow.com/questions/20632149
复制相似问题