Laravel: Sending Mail with Queue ignores Locale


Laravel: Sending Mail with Queue ignores Locale



My Email template looks like this:


@component('mail::message')
# {{ $helloUser }}

@lang('welcome.message')



This


App::setLocale('de);

$activeMail = new AppMailRegisterActivate($user);

Mail::to($user)->send($activeMail);



will send an mail with German text.



However, when I use a queue


App::setLocale('de);

$activeMail = new AppMailRegisterActivate($user);

Mail::to($user)->queue($activeMail);



The mail is send in English, which is the default language of my app.
How can I send a message in German with the queue without changing the default language?




2 Answers
2



In Laravel 5.6. the Mailable class has gotten a locale method to care for this:


Mailable


locale


$activeMail = new AppMailRegisterActivate($user)->locale('tr');

Mail::to($user)->queue($activeMail);



For Laravel < 5.6 you have to save the text in the mail objecte


class Activate extends Mailable
{

public $mainText

public function __construct()
{
$this->mainText = __('welcome.message');
}
}



and change the template to


@component('mail::message')
# {{ $helloUser }}

{{$mainText}}



You have to set the locale in the Job because it is executed on another process and it does not have any session variables or data from the process that sent it to the queue. You can do something like this if you save the locale in the User model:


class Activate extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;

protected $user;

public function __construct(User $user)
{
$this->user = $user;
}

public function build()
{
App::setLocale($this->user->getAttribute('locale')); // locale = 'de'

return $this->subject('Activate your account')->view('emails.activate', [
'user' => $this->user
]);
}
}





The locale is actually saved in the user. But how do you pass the locale to the job?
– Adam
Jun 29 at 9:31





I have added an example to my original answer. This way you can set other user settings or variables that affect the content of the email. Answer by 'Adam' only changes translator locale. It depends of your needs.
– gerardnll
Jun 29 at 13:04







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift