此节复写 trait 中的 notify 方法,会导致框架自带的「重新发送邮件」的功能失效,建议在 user model 类中新增一个 topicNofity 方法单独处理即可。

此节重写了 \Illuminate\Notifications\RoutesNotifications::notify,导致如果是发送给自己的通知,就不会发送 $this->id == Auth::id(),但是激活邮件是需要发送给自己的。所以,最好是不要重写trait中的notify方法,而改为在user model类中新增一个topicNotify()的方法,代码如下:

  • app/Models/User.php

    //    public function notify($instance)
    //    {
    //        // 如果要通知的人是当前用户,就不必通知了!
    //        if ($this->id == Auth::id()) {
    //            return;
    //        }
    //        $this->increment('notification_count');
    //        $this->laravelNotify($instance);
    //    }
    
    public function topicNotify($instance)
    {
        // 如果要通知的人是当前用户,就不必通知了!
        if ($this->id == Auth::id()) {
            return;
        }
        $this->increment('notification_count');
        $this->notify($instance);
    }
  • app/Observers/ReplyObserver.php
    public function created(Reply $reply)
    {
        $topic = $reply->topic;
        $reply->topic->increment('reply_count', 1);
        // 通知作者话题被回复了
        $topic->user->topicNotify(new TopicReplied($reply));
    }
  • 测试「重新发送邮件」和「消息通知」的功能,成功!
日拱一卒
本帖已被设为精华帖!
本帖由系统于 4年前 自动加精
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 11
天上白玉京

找了好久的问题

5年前 评论

5.7版本中似乎有了更好的解法。

5年前 评论

這個問題我也找了好久XD

5年前 评论

对的,这里重写notify并不好,重新写一个通知方法里调用notify()才好

3年前 评论

没搞清楚这里是复现哪里的BUG?

3年前 评论

直接把是否是本人的判断改到 是否是数据库通知判断的分支里面不就解决了

因为密码相关的都是邮件通知

public function notify($instance)
{


    // 只有数据库类型通知才需提醒,直接发送 Email 或者其他的都 Pass
    if (method_exists($instance, 'toDatabase')) {
        // 如果要通知的人是当前用户,就不必通知了!
        if ($this->id == Auth::id()) {
            return;
        }
        $this->increment('notification_count');
    }

    $this->laravelNotify($instance);
}
3年前 评论

@tendollor 感觉这样写不太好 如果以后 还有其他 的通知 也用数据库方式 那这里还得改

2年前 评论

原来这就是重新发送不执行的原因,点赞支持

知道了原因后,我的改正方法如下

// 如果要通知的人是当前用户,且不是在验证邮箱,就不必通知了!
if ($this->id == Auth::id()&&get_class($instance)!="Illuminate\Auth\Notifications\VerifyEmail") {
    return;
}
1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!