我如何将通知的数据更改为 laravel 中评论的数据

问题描述

我设置了通知,以便当用户对其他用户的帖子发表评论时,帖子的所有者会收到通知,让他们知道该评论

但目前通知显示以下内容添加到 return 语句:

public function toArray($notifiable) {
    return [
        'data' => 'Test notification'
    ];
}

但是当用户发表评论时,我想用以下内容替换“测试通知”:

评论帖子的用户姓名,例如:

'John commented on your post'

我该怎么做才能让它始终显示评论者的用户名

如果这对我有帮助,请在构造函数的顶部进行评论和发布,如下所示:

public function __construct(User $user,Post $post,Comment $comment) {

    $this->user = $user;
    $this->comment = $comment;
    $this->post = $post;
}

解决方法

通常 $notifiable 将是 User。因此,如果您的代码是这种情况,您可以使用它。
如果没有,请使用您提供的代码执行类似的操作

public function toArray($notifiable) {
    return [
        'data' => $this->user->username.' commented on your post','email' => $this->user->email
    ];
} 

您可以在此处https://laravel.com/docs/8.x/notifications#using-the-notifiable-trait

了解有关文档中的 $notifiable 的更多信息 ,

看看这篇文章。它可以回答您的所有问题。

the medium blog answer link