My app can change locale using url request.
Route::get('/setLocale/{locale}', function (Request $request, $locale) {
session()->put('locale', $locale);
App::setLocale($locale);
return redirect('/');
})->name('setLocale');
And that locale string would be stored in session. I use middleware to dynamically change locale using the session data if there's any.
public function handle($request, Closure $next)
{
if (session('locale')) {
App::setLocale(session('locale'));
}
return $next($request);
}
The problem is that App::getLocale()
in web.php
always return default locale settings, even when the locale is set to the other one (because I can see different text on web).
$locale = App::getLocale();
dd($locale); // default locale set in config.php
I tried using session('locale')
, but it always return null
. I am pretty sure it's set in session because I can see the website has that locale.
The reason I need reference of locale is because I want to generate dynamic route prefix based on locale.
$locale = App::getLocale();
Route::prefix($locale)->group(function () {
....
});
I am wondering what's the problem here? Is it because session isn't instantiated before routes?
Kernal.php
protected $middlewareGroups = [
'web' => [
... (default)
\App\Http\Middleware\SetLocale::class,
],
];
So I dd() the App::getLocale() on web.php and on my globle web middleware, dd() on web.php gets printed first...
So I get web.php is called before any global middlewares are registerd. But then how can I set dynamic prefix based on locale???
App::getLocale()
? is that inside a route group with the above middleware? – Wreigh