2

我希望为 SEO 目的为电子商务商店扁平化我的路线。

我想创建以下路线:

Route::get('/{country}', ['uses' => 'Store\ProductController@browseCountry']);
Route::get('/{category}, ['uses' => 'Store\ProductController@browseCategory']')

countrycategory必须是动态的。

我想知道类似以下的事情是否可行?以及实现的最佳方式。

// 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');

然而,这是笨拙和乏味的。我想从数据库中获取国家列表。

4

3 回答 3

3

我会这样做我选择国家模型,因为模型较少+您需要缓存它:将列表('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-17T12:41:40.793 回答
0

好的,所以在查看更新后的问题后,您需要在各自的模型中创建一个方法,以将所有可用的 slug 与 | 字符,所以你会调用类似的东西:

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

这几乎会像您的示例一样返回 'great-britain|china|japan|south-africa' ,除非您不必编写它。

但是,我强烈建议您为路线提供更多内容,/country/{country} 或 /category/{category} 否则会令人困惑,并且 URI 结构通常是这样的,以便用户可以准确地看到他们在哪里是。

于 2013-12-17T11:09:17.943 回答
0

您需要路由过滤器来实现这一点。

将以下代码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'));
于 2013-12-17T11:44:21.913 回答