#### 準備數據庫
生成消息通知遷移文件
~~~
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; 修改為以下: