Send queued mails in Laravel with specific language

If you create a mailable class in Laravel, then you either create the content in the constructor, in the the blade or in both. If you want to send your mail in language X in queue then its relevant where the content is created at.

1. Content is in blade file

Assume you have your content of the mail in a blade file:


Then you can either use it on Mail facade


or on the Mailable object

 $test = new \App\Mail\ActiveMail();

But if you use the Mailable, you have to use send from that object. This will not work:


2. Content is setup in constructor

Lets assume the following is your constructor:

public function __construct($user)
      $this->subject = __('list.emailWelcomeSubject', [':user' => $user->getName()]);
      $this->subject = __('list.emailWelcomeMessage');

In this case, the locale method of Mail facade or the Mailable object won't work!
The language has to be set when the Mailable object calls the constructor. Something like this:

public function __construct($user)
      $tmp = \App::getLocale();
      $this->subject = __('list.emailWelcomeSubject', [':user' => $user->getName()]);
      $this->subject = __('list.emailWelcomeMessage');

The solution for 1 & 2

However this might be a bit cumbersome if you need to do this for every mail. I ended up creating a static function that does this sort of things for me whenever I send a mail (which covers both 1 & 2 case):

  public static function to(Sendable $user, String $class, Array $params, $options = [])
    $email    = $options['email']     ?? null;
    $lang     = $options['lang']      ?? null;
    $queue    = $options['queue']     ?? true;
    $restrict = $options['restrict']  ?? null;

    if(empty($email)) $email = $user->getEmail();

    $locale = (empty($lang)) ? $user->getLang() : $lang;

      $locale = (in_array($locale, $restrict)) ? $locale : 'en';

    $temp = \App::getLocale();

    $reflection_class = new \ReflectionClass($class);
    $mailclass = $reflection_class->newInstanceArgs($params);

    $receiver = new \stdClass();
    $receiver->email = $email;
    $receiver->name  = $user->getName();



Leave a comment

Your email address will not be published. Required fields are marked *