首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Laravel消息通知系统之数据库

Laravel消息通知系统之数据库

作者头像
切图仔
发布2022-09-08 19:13:38
发布2022-09-08 19:13:38
1.1K00
代码可运行
举报
文章被收录于专栏:生如夏花绚烂生如夏花绚烂
运行总次数:0
代码可运行

Laravel 自带了一套极具扩展性的消息通知系统,尤其还支持多种通知频道,我们将利用此套系统来向用户发送消息提醒。

通知频道指通知的各种途径,Laravel自带的有如下几种

  1. 数据库
  2. 邮件
  3. 短信(通过 Nexmo)
  4. Slack
通过数据库实现消息通知

1.准备数据表

代码语言:javascript
代码运行次数:0
运行
复制
 php artisan notifications:table

该命令会生成消息通知表的迁移文件

代码语言:javascript
代码运行次数:0
运行
复制
database/migrations/{$timestamp}_create_notifications_table.php

使用命令执行迁移文件

代码语言:javascript
代码运行次数:0
运行
复制
php artisan migrate

2.生成通知类

laravel中每一种通知属于一个类,使用如下命令创建通知类,通知类存放在app/Notifications

代码语言:javascript
代码运行次数:0
运行
复制
 php artisan make:notification TopicReplied

3.定义通知类

代码语言:javascript
代码运行次数:0
运行
复制
<?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.触发通知

在某个模型的观察者中

代码语言:javascript
代码运行次数:0
运行
复制
<?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() ,此方法接收一个通知实例做参数。

这样当评论被写入数据库时,会触发消息通知并写入数据库。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-05-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 通过数据库实现消息通知
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档