#### 准备数据库
生成消息通知迁移文件
~~~
php artisan notifications:table
~~~
进行迁移
~~~
php artisan migrate
~~~
#### 修改user表
用来记录用户有多少条未读信息
~~~
php artisan make:migration add_notification_count_to_users_table --table=users
~~~
#### 生成通知类
此类在app/Notifications 文件夹里
~~~
php artisan make:notification TopicReplied
~~~
代码修改如下,每个通知类都有个 via() 方法,它决定了通知在哪个频道上发送。我们写上 database 数据库来作为通知频道。
因为使用数据库通知频道,我们需要定义 toDatabase()。这个方法接收 $notifiable 实例参数并返回一个普通的 PHP 数组。这个返回的数组将被转成 JSON 格式并存储到通知数据表的 data 字段中。
~~~
class TopicReplied extends Notification
{
use Queueable;
public $reply;
public function __construct(Reply $reply)
{
// 注入回复实体,方便 toDatabase 方法中的使用
$this->reply = $reply;
}
public function via($notifiable)
{
// 开启通知的频道
return ['database'];
}
public function toDatabase($notifiable)
{
$topic = $this->reply->topic;
$link = $topic->link(['#reply' . $this->reply->id]);
// 存入数据库里的数据
return [
'reply_id' => $this->reply->id,
'reply_content' => $this->reply->content,
'user_id' => $this->reply->user->id,
'user_name' => $this->reply->user->name,
'user_avatar' => $this->reply->user->avatar,
'topic_link' => $link,
'topic_id' => $topic->id,
'topic_title' => $topic->title,
];
}
}
~~~
#### 触发通知
我们希望当用户回复主题后,通知到主题作者。故触发通知的时机是:『回复发布成功后』,在模型监控器里,我们可以在 created 方法里实现此部分代码,修改 created() 方法为以下:
~~~
use App\Notifications\TopicReplied;
class ReplyObserver
{
public function created(Reply $reply)
{
$topic = $reply->topic;
$topic->increment('reply_count', 1);
// 通知作者话题被回复了
$topic->user->notify(new TopicReplied($reply));
}
.
.
.
}
~~~
默认的 User 模型中使用了 trait —— Notifiable,它包含着一个可以用来发通知的方法 notify() ,此方法接收一个通知实例做参数。虽然 notify() 已经很方便,但是我们还需要对其进行定制,我们希望每一次在调用 $user->notify() 时,自动将 users 表里的 notification_count +1 ,这样我们就能跟踪用户未读通知了。
打开 User.php 文件,将 use Notifiable; 修改为以下: