关于LARAVEL学习--使用 LARAVEL NOTIFYNDER 扩展轻松实现消息通知
发布于 2021-11-18 16:43 ,所属分类:软件编程学习资料
在Laravel项目中,我们先按照步骤安装Notifynder扩展,步骤如下:
1、使用Composer安装该扩展:
composer require fenos/notifynder
2、然后到config/app.php中注册服务提供者:
Fenos\Notifynder\NotifynderServiceProvider::class,
以及门面:
'Notifynder' => Fenos\Notifynder\Facades\Notifynder::class,
3、发布该扩展包的配置文件到config目录:
php artisan vendor:publish --provider="Fenos\Notifynder\NotifynderServiceProvider"
4、最后运行数据库迁移生成相应数据表:
php artisan migrate
next

完成以上步骤,我们便成功的装完了Notifynder扩展,我们可以在我们的数据库中看到两个表,分别是notification_categories(模板表)、notifications(消息通知表)。
创建发送通知模板,代码如下:
php artisan notifynder:create:category "user.following" "{from.username} started to follow you"
如果报错,可能是版本太高了,那我们可以手动往数据库里添加发送消息模板,截图如下

可以看到第一列是ID、第二列是模板的名称、第三列是模板内容,其中的{from.username}是参数,如果我们想要自定义更多的参数可以参考如下:

Finally

完成消息模板之后,接下来确定要被通知的模型,通常我们选择User模型,这个被选择的模型类要使用 Notifable Trait:,代码如下:
use Fenos\Notifynder\Notifable;
class User extends Model{
use Notifable;
}
这样我们的模型实体就可以发送消息通知了:
$from_user_id = 1; //发送者ID
$to_user_id = 2; //接收者ID
Notifynder::category('user.following')
->from($from_user_id)
->to($to_user_id)
->url('http://laravelacademy.org/notifications')
->extra('upperProject'=>'测试','date'=>'20180725')
->send();
其中的form是发送者ID,to是接收者ID,url是消息附带的跳转地址,extra是参数数组。
发送通知后我们来检索通知:
$userNotified = User::find($to_user_id);
dd($userNotified->getNotificationsNotRead());
如果我们想要查看单条通知的话,代码如下:
$id = $this->id; //获取消息通知ID
$query = Notification::where('id', $id);
$newsDetail = $query->findOrFail($id);
$newsDetail = $newsDetail->text;
相关资源