I am creating a bilingual application in which I have implemented database and e-mail notifications.
A notification is, for example, information that a user has started a new conversation. Unfortunately, notifications sent to the database are sent in the language of the user who sends them (set language: App::setLocale(Auth()->user->locale);
) and not in the language of the recipient.
I use:
use IlluminateContractsTranslationHasLocalePreference;
class User extends Model implements HasLocalePreference
{
/**
* Get the user's preferred locale.
*
* @return string
*/
public function preferredLocale()
{
return $this->locale;
}
}
Oddly enough, email notifications work this way.
I translate notifications like this:
$customer->notify(new NewMessageNotification($message, trans('notifications.new_message', ['user' => $user->name])));
I tried this way, but it didn’t change anything:
https://setkyar.medium.com/fixing-laravels-notification-locale-issue-9ad74c2652ca
Although now I’m wondering if it wouldn’t be better to save in the key base and translate only when reading, so that all received notifications are translated when changing the language. The only question is how to do it then.
2
Answers
I found that I save to the database in both languages and when reading, I check the language set by the user to display the appropriate version.
On second thought, it seems more logical to have notifications displayed in the currently set language rather than when sent.
If i understand well, you want to send notification based on destination language and not based on sender one. If yes, preferredLocale may not works, but you can try to define the language on notification trigger like this: