zoukankan      html  css  js  c++  java
  • 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);
        }
    }
    

      

  • 相关阅读:
    android 读中文文本文件
    Android-将RGB彩色图转换为灰度图
    andriod 获取电池的信息
    android studio快捷键
    2016年深圳市服务业占GDP比重首次突破六成
    三分钟看完北京城市(含京津冀)【总体规划2016-2050】
    CentOS 7.3.1611系统安装配置图解教程
    为何北美华裔二代三代之后长相就跟中国人不一样了?
    别看不起印度,印度比中国好多了?
    东南亚十大城市
  • 原文地址:https://www.cnblogs.com/bing2017/p/8570453.html
Copyright © 2011-2022 走看看