Laravel optional prefix routes with regexp

后端 未结 4 871
野的像风
野的像风 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:22

    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
    });
    
    0 讨论(0)
  • 2021-01-05 17:24

    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();
    
    0 讨论(0)
  • 2021-01-05 17:34

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题