在项目开发时遇到一个问题,需要对系统进行一个站内消息推送,经过查阅官方文档,最终实现了功能。在这里做个记录。
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();
}
以上就是全过程。