简体   繁体   English

Laravel 9、用preferredLocale发送通知

[英]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.不幸的是,发送到数据库的通知是以发送它们的用户的语言发送的(设置语言: App::setLocale(Auth()->user->locale); )而不是以接收者的语言发送。

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.奇怪的是,email 通知以这种方式工作。

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 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:如果是,preferredLocale 可能不起作用,但您可以尝试在通知触发器上定义语言,如下所示:

$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.转念一想,以当前设置的语言显示通知似乎比发送时更合乎逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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