Laravel 自带了一套极具扩展性的消息通知系统,尤其还支持多种通知频道,我们将利用此套系统来向用户发送消息提醒。
通知频道指通知的各种途径,Laravel自带的有如下几种
- 数据库
- 邮件
- 短信(通过 Nexmo)
- Slack
通过数据库实现消息通知
1.准备数据表
php artisan notifications:table
该命令会生成消息通知表的迁移文件
database/migrations/{$timestamp}_create_notifications_table.php
使用命令执行迁移文件
php artisan migrate
2.生成通知类
laravel中每一种通知属于一个类,使用如下命令创建通知类,通知类存放在app/Notifications
php artisan make:notification TopicReplied
3.定义通知类
<?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,
];
}
}
通知类的构造方法可执行依赖注入,via方法表示通过什么途径发送通知,toDatabase是数据库通知的方法,这个方法接收 $notifiable
实例参数并返回一个普通的 PHP 数组。这个返回的数组将被转成 JSON 格式并存储到通知数据表的 data 字段中。
4.触发通知
在某个模型的观察者中
<?php
namespace App\Observers;
use App\Notifications\TopicReplied;
use App\Models\Reply;
// creating, created, updating, updated, saving,
// saved, deleting, deleted, restoring, restored
class ReplyObserver
{
public function created(Reply $reply)
{
$reply->topic->reply_count = $reply->topic->replies->count();
$reply->topic->save();
// 通知话题作者有新的评论
$reply->topic->user->notify(new TopicReplied($reply));
}
其中 User 模型中使用了 trait —— Notifiable,它包含着一个可以用来发通知的方法 notify() ,此方法接收一个通知实例做参数。
这样当评论被写入数据库时,会触发消息通知并写入数据库。