0

I would like to use language selector in Laravel. I used this sollution: Laravel optional prefix routes with regexp. It works fine. I store location in database eg.: en, de. I would like to use the prefix only if the site has multiple language set in database. So how can I prevent use 'prefix' => '{lang?}' if i have only one language.

Here you are my web.php (Route):

Route::group(['prefix' => '{lang?}', 'middleware' => 'locale', 'where' => ['lang' => "en|de"], function () {
    Route::get('/', 'HomeController@index');
    Route::get('article', 'ArticlesControllerController@index');
});

With 1 language:

/home
/article

With multi language:

/en/home
/de/home
/en/article
/de/article
Zsolt Janes
  • 800
  • 2
  • 8
  • 26

1 Answers1

4

Well in this situation, you can use the Closure function and if condition. Set the prefix based on the values as it is possible to declare a Closure with all your routes and add that once with the prefix and once without:

$languageList = 'fr|en';

$optionalLanguageRoutes = function() {
    Route::get('/test', 'DashboardController@test');
};

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

// Add routes without prefix

$optionalLanguageRoutes();

Declare empty languageList when you don't have languages.

Sachin Kumar
  • 3,001
  • 1
  • 22
  • 47