Laravel optional prefix routes with regexp

核能气质少年 提交于 2019-12-22 08:15:12

问题


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(){});

a route like this: /authors/author-100.html will match a prefix 'authors` , and for sure there is no language called "authors".

I use laravel 5.5


回答1:


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.




回答2:


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();



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/46032537/laravel-optional-prefix-routes-with-regexp

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