Laravel optional prefix routes with regexp

后端 未结 4 1025
野的像风
野的像风 2021-01-05 16:48

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/article         


        
4条回答
  •  醉酒成梦
    2021-01-05 17:41

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

    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.

提交回复
热议问题