Home > Software engineering >  Spatie Laravel 9: send email notification to Users with roles
Spatie Laravel 9: send email notification to Users with roles

Time:01-18

I got everything working in terms of sending emails and templating. Now I want to replace the static to: [email protected] with users' email with specific roles.

I have this code written:

 public function envelope()
    {
        return new Envelope(
            from: '[email protected]',
            to: [
                User::with("roles")->whereHas("roles", function($q) {
                    $q->whereIn("id", [
                        1, // Super Admin
                        6, // Admin
                        2, // Security Supervisor
                        5, // Security Manager
                    ]);
                })->get('email')
            ],
            subject: 'New Incident: ' . str_pad($this->record->ir_number, 4, '0', STR_PAD_LEFT) .
                ' - ' .
                $this->record->caseTypeRelationship->name .
                ' - ' . $this->record->locationRelationship->name,
        );
    }

I've made to: as an array to include emails of the provided roles (id). I get an error saying that the address are not correct/doesn't exist. What is the proper way to fetch emails of users of the selected roles?

CodePudding user response:

First of all, you do not need to include roles if you don't need them. It's introducing an additional query which you should avoid.

Secondly, your ->get('email') is returning a Collection of users with only the email field. You probably want to convert that to an array to pass it on to the Envelope.

Thirdly, you have wrapped the output of your ->get('email') which in itself is already a collection in an array of its own, making your email sit a level too deep.

Something like this should do the trick:

to: User::whereHas("roles", function($q) {
  $q->whereIn("id", [1, 6, 2, 5]);
})->pluck('email')->toArray(),

CodePudding user response:

You can get the list of emails with the following and assign it to an array:

$emails = User::role(['Super Admin', 'Admin', 'Security Supervisor', 'Security Manager'])
                     ->pluck('email')->toArray();

then change your to: $emails

  • Related