Search code examples
laravellaravel-7

Route prefix return 404


I'm trying to create an url semantic structure for a multi language site, so in the routes.php file I wrote all the routes in a group like this:

Route::group(['prefix' => '{locale?}', 'middleware' => ['web', 'locale', 'theme', 'currency']], function ($locale) {
    
    Route::get('/', 'HomeController@index')->defaults('_config', [
        'view' => 'shop::home.index'
    ])->name('shop.home.index');
    
});

the behavior of this is kinda weird, infact when I browse the site using this url: example.com (so without the locale prefix), everything working as expected. If instead, I add the locale prefix: example.com/it, I get 404, infact the index method of HomeController is never invoked.

Essentially I want that if you visit the site without prefix, then you will see the default language (en). But if you visit the site using a prefix, then, Laravel should load the locale specified as prefix.


Solution

  • To solve this issue, you can make the {locale} parameter required by removing the question mark (?) from the prefix definition. This way, Laravel will always expect a non-empty prefix and will match the route group correctly.

    Route::group(['prefix' => '{locale}', 'middleware' => ['web', 'locale', 'theme', 'currency']], function ($locale) {
        
        Route::get('/', 'HomeController@index')->defaults('_config', [
            'view' => 'shop::home.index'
        ])->name('shop.home.index');
        
    });