以laravel5.5為例子,這個功能laravel自帶的有:
1.生成表文件的migration文件,再migrate一下在數據庫里生成表.命令為:php artisan notifications:table || php artisan migrate
2.在user表里增加一個notification_count 字段可以為null,
3.因為沒有這個類,所以要生成個通知類:php artisan make:notification TopicReplied
4.類內注入$reply實例:
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use App\Models\Reply; 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, ]; } }
4.觸發通知 :在人家剛回復保存時觸 發;
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)); } }
5.當有多個通知時,自動給用戶里的通知數量+1
use Auth; class User extends Authenticatable { use Notifiable { notify as protected laravelNotify; } public function notify($instance) { // 如果要通知的人是當前用戶,就不必通知了! if ($this->id == Auth::id()) { return; } $this->increment('notification_count'); $this->laravelNotify($instance); } }