laraveleloquentlaravel-notification

Access individual data in a collection passing to Notification method


I have queried a list of users based on a filter to send out notifications and i want to use this collection method to send out the notification.

Collection method

As in the documentation i pass the users collection to the notification and my post data

Notification::send($users, new PostAlert($post));

I believe, this collection method is firing notifications in a loop. One-by-one.If it is, how do i access a user's details inside the notification ? i can only access $post details for now

Notification::send($users, new PostAlert($users, $post));

Doing the above passes the collection and i cannot access a single user detail inside the notification.

I know that i can set the firing on a loop, but i believe it is not the cleanest way

foreach($users as $user) 
{
   Notification::send(new PostAlert($user, $post));
}

It would be very helpful if you could help me how would i access a single model passing from collection.


Solution

  • It is pretty easy, Try it,

    You will find a variable called $notifiable

    // PostAlert
    ...
    // toMail() or toArray()
    public function toMail($notifiable)
    {
        dd($notifiable,"the user laravel is sending to.");
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }
    ...
    

    Happy Codding.