根据自定义用户区域设置值发送 Laravel 条通知

Send Laravel notifications according to custom user locale value

我正在寻找根据用户区域设置值(英语和西班牙语)在 Laravel 中构建通知的最佳方法。

SomeController.php(发送通知):

Notification::send(User::find($some_id), new CustomNotification($some_parameter));

CustomNotification.php:

class CustomNotification extends Notification
{
    use Queueable;
    protected $title, $body, $foot;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($some_parameter)
    {
        $this->title = __('Some Title');
        $this->response = __('Some Response');
        $this->foot = 'My WebPage Title';
    }
    ...
}

使用 CustomNotification 构造,$title 和 $response 的值将根据发送通知的当前用户进行转换,但在这种情况下,管理员是发送通知的人,因此该变量的值将在管理员语言环境中,而不是在用户中。

好吧,在这种情况下,您应该将语言环境存储在用户 table 中,然后您可以将它(或至少是他的语言环境)发送到通知构造函数:

$user=User::find($some_id);

Notification::send($user, new CustomNotification($some_parameter,$user));

并在您的通知中 class:

class CustomNotification extends Notification
{
    use Queueable;
    protected $title, $body, $foot;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($some_parameter,User $user)
    {
       
        App::setLocale($user->locale??$defaultLocale);

        $this->title = __('Some Title');
        $this->response = __('Some Response');
        $this->foot = 'My WebPage Title';
    }
    ...
}

也喜欢@ManojKiran Appathurai,你使用laravel notification localization:

 Notification::send($user, new CustomNotification($some_parameter)->locale($user->locale);