Laravel进阶系列笔记--(二十六)Laravel 基于Notification数据库通知的快速使用
作者:温新
时间:2021-08-01
hi,我是温新,一-名PHPer。
本系列采用Laravel8.x演示。
基于数据库的通知可以将通知存储入数据表中,表中包含了通知类型及用于描述通知的自定义JSON数据之类的信息。这个不需要我们创建,使用Laravel命令可以帮我们自动创建。
本篇案例目标是模拟用户注册后,再个人中心中提示注册成功的消息,默认为未读状态。
快速使用数据库通知
第一步:生成通知表
php artisan notifications:table
    
php artisan migrate
执行完之后会生成一个
notifications表,关于生成的数据表字段一定要看,我不列表出来了。
第二步:生成通知类
php artisan make:notification DbSendUser
第三步:修改通知类为数据库通知
// Notifications/DbSendUser.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class DbSendUser extends Notification
{
    use Queueable;
    public $user = null;
    public function __construct($user)
    {
        $this->user = $user;
    }
    
	// 修改为数据库通知
    public function via($notifiable)
    {
        return ['database'];
    }
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }
    public function toArray($notifiable)
    {
        return [];
    }
    
    // 将通知存入数据库的方法
    public function toDatabase($notifiable)
    {       
    }
}
第四步:定义路由
// web.php
Route::get('send','TestController@send');
Route::get('look','TestController@look');
第五步:创建控制器及方法
控制器
php artisan make:controller TestController
方法
// TestController.php
public function send(){}
// 查看通知
public function look(){}
第六步:模拟用户注册
// TestController.php
use App\Models\User;
use App\Notifications\DbSendUser;
use Illuminate\Support\Facades\Notification;
public function send()
{
    // 模拟用户注册
    $user = User::create([
        'name'  =>  '财迷',
        'email' =>  '12345678@qq.com',
        'password' =>  encrypt('123456'),
    ]);
    Notification::send($user, new DbSendUser($user));
}
第七步:将通知数据表
// Notifications/DbSendUser.php
public function toDatabase($notifiable)
{
    // 数据会以JSON格式存入表中
    return [
        'user_id'   =>  $this->id,
        'email'     =>  $notifiable->email,
        'msg'       =>  '注册成功'
    ];
}
第八步:访问路由模拟注册
你的域名/send,访问之后用户注册成功,相对应的通知也会存入表中。
如此,通知已经完成,接下来就是对通知的操作的。关于通知还有很多复杂的操作,这需要不断的深入学习。简单的基础的使用也就到这里了。
数据库通知的其它操作
notifications动态属性访问通知
修改控制器中的look方法
// TestController.php
public function look()
{
    $user = User::find(10);
    foreach ($user->notifications as $notification) {
        dump($notification);
    }
}
unreadNotifications动态属性将所有通知标记为已读
// TestController.php
public function look()
{
    $user = User::find(10);
    // 将通知标记为已读
    $user->unreadNotifications->markAsRead();
}
通知的数据表中有一个read_at字段,通知标记已读会将当前时间更新到read_at字段,表示该通知已经被读过。
我是温新
每天进步一点点,就一点点
请登录后再评论