mahmoud
mahmoud

Reputation: 23

Notify Comment owner when a reply is submitted [LARAVEL]

I have 2 tables comments and Replies related as follows :

Reply.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');}

I am trying to create a notification .. when a user replies on a specific comment .. the comment owner gets notified.

so I created a new notification called 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
        ];
    }

and in my 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 now is working , but as you can see the "Reply Owner " is the one being notified as defined in the function.. I tried to change Auth:: user to something like $reply->comment->user , but this gives me error ..

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

How to define the comment owner to notify instead of auth user ?

Upvotes: 1

Views: 513

Answers (1)

Henry Bui
Henry Bui

Reputation: 703

You are passing the empty $reply to RepliedToCommend() function, that's why it cannot get the user and return error.

Change code to:

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: The code has not been tested! Please test it yourself.

Upvotes: 1

Related Questions