Laravel 5.7 Mail Localization Improvements

Laravel 5.7 Mail Localization Improvements

Laravel 5.7.7 is now released and includes both bug fixes and thanks to Derek MacDonald a big improvement to Mail Localization.

With the release of Laravel 5.7 the Illuminate\Notifications\Notification class started offering a locale method to set the desired language. The application will change into this locale when the notification is being formatted and then revert back to the previous locale when formatting is complete. Here is an example of this feature:

$user->notify((new InvoicePaid($invoice))->locale('es'));

Now with Laravel 5.7.7 you can take this a step further and hook directly into a “user” model. In a typical application you might have a “locale” field on the user table and now you can define the User model as follows:

use Illuminate\Contracts\Translation\HasLocalePreference;

class User extends Model implements HasLocalePreference
    public function preferredLocale()
        return $this->locale;

Now pretend you create a user from Germany:

$user = User::create([
    'email' => '',
    'locale' => 'de',

The following four calls will send the notification to the user in German:

$user->notify(new OrderConfirmation($order))
Notification::send($user, new OrderConfirmation($order))
Mail::to($user)->queue(new OrderConfirmation($order)
Mail::to($user)->send(new OrderConfirmation($order)

Of course, if you need to over-ride a user locale preference you can by specifying the locale() like this:

$user->notify((new OrderConfirmation($order))->locale('en'))

As you can see, the inclusion of this feature will allow you to simplify a lot of your code when sending emails to people throughout the world. For complete information on this check out the pull request which includes great documentation and a complete changelog on how it’s implemented.

Filed in: Laravel 5.7


Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Lead Front End Developer
Full-Stack Laravel Developer
Revive Interior
Intermediate PHP Developer (Full Stack | CakePHP | Laravel | Vue | jQuery)
Senior PHP Developer (Full Stack | CakePHP | Laravel | Vue | jQuery)
Laravel Developer
Amsterdam (partially remote possible)
Let's Book
Web Developer (Laravel)
Tweed Heads, New South Wales, AUSTRALIA
Tursa Employment & Training
Laravel Experts needed-Remote position
Golden Sky ROI