I am trying to set app locale in Laravel 11 with Inertia.js.
Here is the links to set locale:
<DropdownLink :href="route('set-language', { lang: 'lv' })">
<div class="flex items-center">
<img src="../../images/icons/latvian.png" :alt="$t('locales.lv')" height="25px" width="25px">
<span class="ml-2">{{ $t('locales.lv') }}</span>
</div>
</DropdownLink>
<DropdownLink :href="route('set-language', { lang: 'en' })">
<div class="flex items-center">
<img src="../../images/icons/english.png" :alt="$t('locales.en')" height="25px" width="25px">
<span class="ml-2">{{ $t('locales.en') }}</span>
</div>
</DropdownLink>
Controller action:
public function setLanguage(string $lang)
{
Session::put('language', $lang);
return Inertia::location(url()->previous());
}
Middleware (added to controller’s action route):
public function handle(Request $request, Closure $next)
{
if (Session::has('language')){
App::setLocale(Session::get('language'));
}
return $next($request)
->withCookie(
cookie()->forever(
'language',
Session::has('language') ? Session::get('language') : 'lv',
null,
null,
null,
false
)
);
}
App starting point:
const getLocale = (localeCookie) => {
const localeName = document.cookie.match(new RegExp('(^| )' + localeCookie + '=([^;]+)'));
return localeName
? localeName[2]
: 'lv';
};
const locale = getLocale('language');
const i18n = setupI18n({locale});
loadLocaleMessages(i18n, locale);
const { t } = i18n.global;
The problem is that locale in laravel is not setting. I have dd() app locale and it’s correct but in application it still remains ‘en’.
So in my language selector where I conditionally show language flag, it’s always showing english flag.
<div class="flex items-center">
<img v-if="$page.props.locale === 'en'" src="../../images/icons/english.png" :alt="$t('locales.en')" height="25px" width="25px">
<img v-if="$page.props.locale === 'lv'" src="../../images/icons/latvian.png" :alt="$t('locales.lv')" height="25px" width="25px">
</div>