S
S
Sergey delphinpro2021-12-12 09:45:55
Laravel
Sergey delphinpro, 2021-12-12 09:45:55

What practices are used for email localization in Laravel?

There is a multilingual site. The user can select the language, letters can be sent to the user. Letters must be sent in the language selected by the user.

How I see it:
Create letter templates for each language

views/emails
  en/
    welcome.blade.php
  ru/
    welcome.blade.php
  ar/
    welcome.blade.php


For convenience, I have added a small trait

trait TranslatableMail
{
  protected function localizedView($name, $locale = null): string
  {
    $localizedView = 'emails.'.($locale ?? $this->user->language).'.'.$name;
    return View::exists($localizedView) ? $localizedView : 'mails.en.'.$name;
  }
}


And I mix in my Mailable classes

class WelcomeMail extends Mailable implements ShouldQueue
{
  use Queueable, SerializesModels;
  use TranslatableMail;
  public function build(): WelcomeMail {
    return $this->from(config('mail.from.address'), config('mail.from.name'))
      ->subject(__('mail.subject.welcome', [], $this->user->language))
      ->view($this->localizedView('welcome'));
  }
}


In principle, everything works, but maybe there are some generally accepted practices?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2021-12-14
@jazzus

The best practice can be found in Laravel itself https://github.com/laravel/framework/blob/b1257c4e...
Translations for many languages ​​with blocks of large text can be placed in short keys of language php files. Example here https://laravel.com/docs/8.x/localization#using-sh...
The author, as a reader of the documentation (I would like to believe not vertically), should know all this. And do not tell nonsense about unknown "real projects". These tools are made for real projects, not virtual ones. Bicycles on real projects are written from ignorance of the framework and inability to use it, and not because there is such a need. These are the letters that I, Laravel, write and see in various packages and projects. I have never seen 1000 views for 10 letters, but I can imagine what kind of crap it is to support.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question