【问题标题】:Notify Comment owner when a reply is submitted [LARAVEL]提交回复时通知评论所有者 [LARAVEL]
【发布时间】:2021-01-27 01:45:07
【问题描述】:

我有 2 个表 cmets 和相关回复如下:

回复.php

    public function user(){return $this->belongsTo('App\User');}
    public function comment(){return $this->belongsTo('App\Comment');}

comment.php

 public function user(){return $this->belongsTo('App\User');}
 public function replies(){return $this->hasMany('App\Reply');}
  • 回复表有:comment_id |用户 ID
  • cmets 表有:user_id

我正在尝试创建通知..当用户回复特定评论时..评论所有者会收到通知。

所以我创建了一个名为 RepliedToComment.php 的新通知

    public function __construct($reply)
    {
        $this->reply=$reply; 
    }

public function via($notifiable)
    {
        return ['mail','database'];
    }

public function toDatabase($notifiable)
    {
        return [
            'repliedTime'=>Carbon::now(),
            'reply'=>$this->reply, 
            'user'=>$notifiable
        ];
    }

在我的 RepliesController.php 中:

  public function store(Request $request, Reply $reply)
    {
        Reply::create($request->all());

        auth()->user()->notify(new RepliedToComment($reply));
        
        return redirect()->back()->with('success', 'Reply Submitted Successfuly');
    }

Notifications 现在正在工作,但正如您所见,“回复所有者”是函数中定义的被通知的对象。我试图将 Auth::user 更改为 $reply->comment->user 之类的东西,但这给了我错误..

ErrorException
Trying to get property 'user' of non-object

如何定义要通知的评论所有者而不是授权用户?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您将空 $reply 传递给 RepliedToCommend() 函数,这就是它无法获取用户并返回错误的原因。

    将代码更改为:

    public function store(Request $request)
    {
        $reply = Reply::create($request->all());
    
        if ($reply && $reply->comment && $reply->comment->user) {
            $reply->comment->user->notify(new RepliedToComment($reply));
            
            return redirect()->back()->with('success', 'Reply Submitted Successfuly');
        }
        return redirect()->back()->withErrors(['error' => 'Something wrong while creating reply!']);
    }
    

    P/s:代码未经测试!请自行测试。

    【讨论】:

    • Henry 非常感谢...按预期工作.. 赞赏 :)
    猜你喜欢
    • 1970-01-01
    • 2011-04-18
    • 2013-03-20
    • 2015-12-19
    • 1970-01-01
    • 2020-03-29
    • 2021-02-20
    • 2014-03-20
    • 2016-06-10
    相关资源
    最近更新 更多