I am using laravel-gettext in my L5 project, but I need to change the locale in the middle of code, just for one part, and then change it back.
I am sending email notification to both customer and owner, this email is using a View to generate the content, but customer and owner can each have different language.
I tried something like this:
$current_locale = \App::getLocale();
$owner_locale = 'cs';
\App::setLocale($owner_locale);
event(new OrderCreated()); // Sends the email
\App::setLocale($current_locale);
Unfortunately this doesn't work, It seems as soon as I change the language at the beginning of the code I can't change it again for part of the code. Is there any other way how to tell the code to use specific gettext language only for specific view? Thanks
Instead of changing the locale you can pass the owner locale to View and use:
Lang::get('file.key', [], $locale);
So this actually works, but I was using the wrong setLocale()
.
As it turns out, LaravelGettext::setLocale()
synchronizes the App::setLocale()
, but not the other way around.
This is the code that works:
$current_locale = \LaravelGettext::getLocale();
foreach ($admins as $admin) {
$admin_locale = $admin->language->locale;
\LaravelGettext::setLocale($admin_locale);
$this->sendTo($admin->email, $subject, $view, $data);
}
\LaravelGettext::setLocale($current_locale);