有没有办法创建带前缀的路线,所以我可以有这样的路线
/articles.html -> goes to listing Controller in default language
/en/articles.html -> goes to the same controller
/fr/articles.html -> goes to the same controller
我目前的问题是通过这样做:
Route::group(['prefix=>'/{$lang?}/',function(){});
像这样的路线:/authors/author-100.html
将匹配前缀'authors`,并且肯定没有称为“作者”的语言。
我用laravel 5.5
使用可选路由参数上Regex匹配的位置应该足够了:
Route::get('/{lang?}, 'SameController@doMagic')->where('lang', 'en|fr');
您也可以在路由组上执行相同的操作,否则具有in this answer的所有选项显然都有效。
显示前缀使用的更新:
Route::group(['prefix' => '{lang?}', 'where' => ['lang' => 'en|fr']],function (){
Route::get('', 'SameController@doNinja');
});
就我而言,即使没有lang也没有lang,这应该足够了,也许这个群体可能会在其他路线之前到来。
似乎没有任何好方法可以使用可选前缀,因为使用“可选”正则表达式标记的组前缀方法不起作用。但是,可以使用所有路由声明一个Closure,并使用前缀添加一次,而不添加一次:
$optionalLanguageRoutes = function() {
// add routes here
}
// Add routes with lang-prefix
Route::group(
['prefix' => '/{lang}/', 'where' => ['lang' => 'fr|en']],
$optionalLanguageRoutes
);
// Add routes without prefix
$optionalLanguageRoutes();
您可以使用表来定义接受的语言,然后:
Route::group([
'prefix' => '/{lang?}',
'where' => ['lang' => 'exists:languages,short_name'],
], function() {
// Define Routes Here
});
另一个可行的解决方案是创建一个langs数组并在其上循环:
$langs = ['en', 'fr', ''];
foreach($langs as $lang) {
Route::get($lang . "/articles", "SomeController@someMethod");
}
这肯定会使您的路线文件的可读性降低,但您可以使用php artisan route:list
清楚地列出您的路线。