0

possible duplicate: How to solve Call to a member function notify() on array? (laravel 5.3)

I am trying to send a database notification to users with admin roles. Since I am using Filament, I also followed the documentation of notifications

First I created a variable called recipients:

$recipients = User::whereHas("roles", function($q) {
            $q->whereIn("id", [
                1, // Super Admin
                6, // Admin
                2, // Security Supervisor
                5, // Security Manager
            ]);
        })->pluck('email')->toArray();

To check users with the roles id and pluck their emails into an array.

Then I did:

$recipients->notify(
        Notification::make()
         ->title('New Incident Created')
         ->icon('heroicon-o-document-text')
         ->toDatabase(),
        );

I get an error: Call to a member function notify() on array.

Abdulrahman Mushref
  • 1,012
  • 2
  • 18
  • 40
  • 1
    If i understand correctly, $recipients is an array with emails. An array does not have method notify(). Try to get Users as collection and then use method each() where you notify each of them individually. – StewieSWS Jan 18 '23 at 08:48

1 Answers1

3

You are doing the notify on an array, also notify needs to be called on the User model as it implements the Notifiable trait: use Notifiable https://laravel.com/docs/9.x/notifications#using-the-notifiable-trait

$recipients = User::role(['Super Admin', 'Admin', 'Security Supervisor', 'Security Manager'])->get();

foreach($recipients as $recipient){
    $recipient->notify(
        Notification::make()
         ->title('New Incident Created')
         ->icon('heroicon-o-document-text')
         ->toDatabase(),
        );  
}
RG Servers
  • 1,726
  • 2
  • 11
  • 27
  • You could use `$recipients->each(fn ($recipient) => $recipient->notify(...));` instead of a foreach loop to be a bit more fluent with the collection. – Jason Aug 23 '23 at 13:35