Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rfountain's avatar

Sending Mail to Multiple Recipients

I have a contact form on my site. When a user submits the form I would like to send an email to all the "site owners". I have the user roles relationships setup and that works fine. I have no issues querying the Owners but I can't seem to send an email to that collection. Here's my code

$user = Role::with('users')->where('name','Owner')->get();

Mail::to($user)->send(new ContactFormSubmitted($request));

The error i'm receiving is

Address in mailbox given [] does not comply with RFC 2822, 3.6.2.

How can I send the email to all site owners?

0 likes
9 replies
ejdelmonico's avatar

Are you separating the group emails with a comma? Also, that box means empty array of data. An array of data is required for the 2nd argument. Please post your code for ContactFormSubmitted.

rfountain's avatar

if I run that query and dd the output I get a collection of users as a result. Now granted the collection seems to be buried a few levels down the dumped results. Maybe i'm not calling the collection correctly. Should it be

$users->SOMETHING

instead of just

$users
TxNuno's avatar

Paste in what is getting dumped when you dd($users); if the collection is nested, then $user->NAMEOFCOLLECTION should work.

ejdelmonico's avatar

I'm a bit confused. How did you end up with a collection? Are you using query builder? Where is the code that connected the returned dataset to a collection? I think you may be confusing the terms which creates a huge difference in approaching the problem.

If you grab that dataset and make a new collection out of the nested array that you need, I think that will solve your issue. If its already a collection from query builder or eloquent, you can flatten the multi-dimensional array with the flatten() method. This method works on Laravel Collections.

Snapey's avatar

You are getting the role with its users

try

Mail::to($user->users)->send(new ContactFormSubmitted($request));

but ideally change it so that it is clear;

$role = Role::with('users')->where('name','Owner')->get();

Mail::to($role->users)->send(new ContactFormSubmitted($request));
1 like
rfountain's avatar

@ejdelmonico I think you're right. I'm returning an eloquent result but the data I'm looking for is nested deep in the returned results. I need to extract that and use that collection.

rfountain's avatar
rfountain
OP
Best Answer
Level 16

I think I figured this out. I wrote the query differently and got an array of users that match. Here's what I did

$users = User::whereHas(
        'roles', function($q) {
            $q->where('name','Owner');
        }
    )->get()->toArray();

After fixing the query, the emails are sent as expected. Thanks everyone for your help

Please or to participate in this conversation.