laravel6 消息通知模块开发

在项目开发时遇到一个问题,需要对系统进行一个站内消息推送,经过查阅官方文档,最终实现了功能。在这里做个记录。
1.首先进行数据表的创建以及迁移。

php artisan notifications:table
php artisan migrate

2.生成消息通知类.

php artisan make:notification MaintainNotice

3.编辑通知类
如果implements ShouldQueue这个接口的话就会异步队列执行,如果去掉的话就是同步执行。

<?php

namespace App\Notifications;

use App\Models\DeviceInfo;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class MaintainNotice extends Notification implements ShouldQueue
{
    use Queueable;

    public $notice;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($notice)
    {
        $this->notice = $notice;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * 使用 database 通道需要定义 toDatabase 方法
     * @param $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        // 将会存入 notifications 表的 data 字段中
        return [
            'notice_id' => $this->notice->id, // 通知ID
            'type' => '通知类型', // 通知类型
            'title' => '通知标题',// 通知标题
            'content' => $this->notice->maintain_mode,// 通知内容
        ];
    }

}

via() 方法,它决定了通知在哪个频道上发送。
4.创建观察者

php artisan make:observer MaintainNoticeObserver

之后编辑观察者事件。

<?php

namespace App\Observers;

use App\Models\PortalMaintainRecord;
use App\Notifications\MaintainNotice;
use App\Models\User;

class MaintainNoticeObserver
{
    /**
     * 处理 Notice 「created」事件
     */
    public function created(PortalMaintainRecord $maintainRecord)
    {
    	//这个是通知的单个用户,
        $user = User::find($id);
        if($user) {
            $user->notify(new MaintainNotice($maintainRecord)); // 发送通知
        }
        //这是全体通知
       $users = User:all();
       foreach($users as $user){
       		$user->notify(new MaintainNotice($maintainRecord)); // 发送通知
       }

    }
}

之后需要注册观察者示例,在AppServiceProvider.php中修改

public function boot()
{
   // ...
   PortalMaintainRecord::observe(MaintainNoticeObserver::class);
}

获取通知

$user = User::find(1);

foreach ($user->notifications as $notification) {
    echo $notification->type;
}

获取未读通知

$user = User::find(1);

foreach ($user->unreadNotifications as $notification) {
    echo $notification->type;
}

标记通知已读

$user = User::find(1);

foreach ($user->unreadNotifications as $notification) {
    $notification->markAsRead();
}

以上就是全过程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值