How do i change the data of my notification to be the data from the comment in laravel

206 views Asked by At

I have set up notifications so that when a user comments on another users post the owner of the post receives a notification to let them know of the comment.

but at the moment the notification just says displays what is added to the return statement in the following:

public function toArray($notifiable) {
    return [
        'data' => 'Test notification'
    ];
}

But when a user posts a comment i want to replace the 'Test notification' with the following:

the name of the user that commented on the post saying for example:

'John commented on your post'

how do i do this so that it always displays the users name of the person thats commented.

if this helps i have passed in the user, comment and post at the top in the construct function like this:

public function __construct(User $user, Post $post, Comment $comment) {

    $this->user = $user;
    $this->comment = $comment;
    $this->post = $post;
}
2

There are 2 answers

3
ml59 On BEST ANSWER

Usually the $notifiable will be the User. So you can use it if this is the case with your code.
If not, working with the code you provided you will do something like that

public function toArray($notifiable) {
    return [
        'data' => $this->user->username.' commented on your post',
        'email' => $this->user->email
    ];
} 

You can learn more about the $notifiable on the doc here https://laravel.com/docs/8.x/notifications#using-the-notifiable-trait

3
Daniyal Ishaq On

have a look at this article. it has answers to all of your questions.

the medium blog answer link