简体   繁体   中英

Laravel 9, send notification with preferredLocale

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 Illuminate\Contracts\Translation\HasLocalePreference;
 
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.

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:

$customer->notify(new NewMessageNotification($message, trans('notifications.new_message', ['user' => $user->name]))->locale('pt'));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM