• laravel中消息通知功能


    以laravel5.5为例子,这个功能laravel自带的有:

    1.生成表文件的migration文件,再migrate一下在数据库里生成表.命令为:php artisan notifications:table    ||    php artisan migrate

    2.在user表里增加一个notification_count 字段可以为null,

    3.因为没有这个类,所以要生成个通知类:php artisan make:notification TopicReplied

    4.类内注入$reply实例:

    <?php
    
    namespace AppNotifications;
    
    use IlluminateBusQueueable;
    use IlluminateNotificationsNotification;
    use IlluminateContractsQueueShouldQueue;
    use IlluminateNotificationsMessagesMailMessage;
    use AppModelsReply;
    
    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,
            ];
        }
    }
    

      4.触发通知 :在人家刚回复保存时触 发;

    use AppNotificationsTopicReplied;
    
    class ReplyObserver
    {
        public function created(Reply $reply)
        {
            $topic = $reply->topic;
            $topic->increment('reply_count', 1);
    
            // 通知作者话题被回复了
            $topic->user->notify(new TopicReplied($reply));
        }
    
    }
    

      5.当有多个通知时,自动给用户里的通知数量+1

    use Auth;
    
    class User extends Authenticatable
    {
        use Notifiable {
            notify as protected laravelNotify;
        }
        public function notify($instance)
        {
            // 如果要通知的人是当前用户,就不必通知了!
            if ($this->id == Auth::id()) {
                return;
            }
            $this->increment('notification_count');
            $this->laravelNotify($instance);
        }
    }
    

      

  • 相关阅读:
    P5737 【深基7.例3】闰年展示
    P1200 [USACO1.1]你的飞碟在这儿Your Ride Is Here
    P1597 语句解析
    P5735 【深基7.例1】距离函数
    P1553 数字反转(升级版)
    P1598 垂直柱状图
    P1603 斯诺登的密码
    P5738 【深基7.例4】歌唱比赛
    Ext.GridPanel 用法总结(一)—— Grid基本用法
    使用CodeSmith快速规范开发.Net软件
  • 原文地址:https://www.cnblogs.com/bing2017/p/8570453.html
Copyright © 2020-2023  润新知