Laravel optional prefix routes with regexp

喜欢而已 提交于 2019-12-05 14:36:46

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.

There doesn't seem to be any good way to have optional prefixes as the group prefix approach with an "optional" regex marker doesn't work. However it is possible to declare a Closure with all your routes and add that once with the prefix and once without:

$optionalLanguageRoutes = function() {
    // add routes here
}

// Add routes with lang-prefix
Route::group(
    ['prefix' => '/{lang}/', 'where' => ['lang' => 'fr|en']],
    $optionalLanguageRoutes
);

// Add routes without prefix
$optionalLanguageRoutes();

You can use a table to define the accepted languages and then:

Route::group([
    'prefix' => '/{lang?}',
    'where' => ['lang' => 'exists:languages,short_name'],
], function() {

    // Define Routes Here
});

Another working solution would be to create an array of langs and loop over it:

$langs = ['en', 'fr', ''];

foreach($langs as $lang) {
  Route::get($lang . "/articles", "SomeController@someMethod");
}

For sure this makes your route file less readable, however you may use php artisan route:list to clearly list your routes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!