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

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.