Home > database >  Laravel 9: send database notifications to users with roles
Laravel 9: send database notifications to users with roles

Time:01-18

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.

CodePudding user response:

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(),
        );  
}
  • Related