In our multi language Laravel application, we want to send emails to user on his language. To make this happen, somehow we have to pass user locale to every queued mail.  Here is how!

 

 

In this tutorial we will localize all queued emails to user's language by using Laravel built in feature for this: Preferred Locales

Preferred Locales

According to Laravel documentation,  by implementing preferredLocale() Laravel will automatically use the preferred locale language when sending notifications and mailables to the model.

So if we are sending email to the user, we have to add HasLocalePreference contract to User model and ad the method which will return the user language.

Let's assume your are storing user language code to users table in field locale, in this case your User model will look like this:

                    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;
    }
}
                  

 

OK, how to pass this preferred language the email notification?
...well you do not have to, Laravel will do it for you.

All you need to do now, is call your notification event. For example like this:

                    $user->notify(new PaymentNotification($event);
                  

Where your toMail method can look like this:

                    public function toMail($notifiable)
    {
            return (new MailMessage)
                ->subject(config('app.name').' '.__('app.Thanks for your order'))
                ->greeting(__('app.Hello'))
                ->line(__('app.Thanks for ordering the product from our store'))
                ->line(__('app.Regards,'))
                ->salutation(config('app.name'))
            ;
    }
                  

 

As you can see, we can simple translate / localize  emails to user preferred language and use it in every mail notification just by setting preferredLocale() on user model.

 

If you want to find out how to put custom translation strings to Laravel mail templates, check this link: