Adam
Adam

Reputation: 29069

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 \App\Mail\Register\Activate($user);

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

will send an mail with German text.

However, when I use a queue

\App::setLocale('de);

$activeMail =  new \App\Mail\Register\Activate($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?

Upvotes: 1

Views: 1533

Answers (2)

gerardnll
gerardnll

Reputation: 2225

Since Laravel 5.7, there's something that can help you with that. Take a look at Localizing Mailables in the documentation.

use Illuminate\Contracts\Translation\HasLocalePreference;

class User extends Model implements HasLocalePreference
{
    /**
     * Get the user's preferred locale.
     *
     * @return string
     */
    public function preferredLocale()
    {
        return $this->locale;
    }
}

Upvotes: -1

Adam
Adam

Reputation: 29069

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

$activeMail =  new \App\Mail\Register\Activate($user);
$locale     =  $user->lang; // de 

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

For Laravel < 5.6 one could save the text in the mail object

class Activate extends Mailable
{

  public $mainText

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

and change the template to

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

{{$mainText}}

The difference is that $mainText is the string from the language when the mail object was created, while @lang('welcome.message') would be the string of the default language from your app.

Upvotes: 2

Related Questions