How to use a dynamic variable in Laravel group routes?

eg:

 Route::group(['prefix' => '{lang?}'], function () {
 //..
 });

create a variable in middleware:

public function handle($request, Closure $next){

$lang = session('locale');

App::setLocale($lang);

return $next($request);      
});

also tried to get data in prefix but got null

Route::group(['prefix' =>  config('app.locale')], function () {
//..
});

or

Route::group(['prefix' =>  session('locale')], function () {
//..
});

change language on a separate route through the session

Route::get('setlocale/{locale}', function ($locale) {

session(['locale' => $locale]);

return redirect()->back();

})->name('setlocale');

Thank you in advance for your help.

+4
source share
1 answer

You do not need to group routes by route lang, you can create your own middleware and group your routes under this middleware and use this code inside it:

public function handle($request, Closure $next){
     $lang = request->get('locale');
     $currentLang = App::getLocale();

     //If locale exists in the url and it changed
     if($lang && $lang != $currentLang) App::setLocale($lang);

     //If locale doesn't exist in the url, fallback to default locale
     if(!$lang) App::setLocale('en');

     return $next($request);      
 });

URL should be data/store?locale=en, ur url should always add localeafter ?in url, otherwise your localedefault will be used

EDIT: locale URL-, , , , : Laravel localization mcmara

+4

Source: https://habr.com/ru/post/1693623/


All Articles