Laravel使用regexp的可选前缀路由 [英] Laravel optional prefix routes with regexp
问题描述
有没有一种方法可以创建带有前缀的路由,这样我就可以拥有这样的路由
Is there a way to create routes with prefixes so I can have routes like this
/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
我当前的问题是这样做:
My current problem is that by doing:
Route::group(['prefix=>'/{$lang?}/',function(){});
这样的路由:/authors/author-100.html
将匹配前缀'authors',并且肯定没有称为"authors"的语言.
a route like this: /authors/author-100.html
will match a prefix 'authors` , and for sure there is no language called "authors".
我使用laravel 5.5
I use laravel 5.5
推荐答案
使用可选的route参数上的where Regex匹配,这应该足够了:
This should be sufficient using the where Regex match on the optional route parameter:
Route::get('/{lang?}, 'SameController@doMagic')->where('lang', 'en|fr');
您也可以在路由组上执行相同的操作,否则显然可以使用此答案中的所有选项.
You can do the same on Route Group as well, else having all the options as in this answer evidently works.
更新以显示前缀的使用:
An update to show the use of prefix:
Route::group(['prefix' => '{lang?}', 'where' => ['lang' => 'en|fr']],function (){
Route::get('', 'SameController@doNinja');
});
就我而言,即使没有lang也有足够的语言,这应该足够了,也许这组语言可能早于其他路线.
As far as I am concerned this should be sufficient even when there is no lang as well as when there is one, just maybe this group could come before other routes.
这篇关于Laravel使用regexp的可选前缀路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!