Laravel Conditional Notifcations

410 views Asked by At

I'm trying to send notifications to multiple users based on several conditions. If one or more conditions are met I'd like to add those users to the array of users that will be sent notifications. The issue is how do I add all of the users from each condition into the final array?

I have users - $data['salesman'] in my case - that get added from the input. Then I have more users I want to add to the array that are static based on the $data['branch'] field of the form.

            // Find selected salesman to send notifications
            $users = User::whereIn('name', $data['salesman'])->get();

            // Send to appropriate people at selected branch
            if($data['branch'] === 'Richmond') {
                $users = User::whereIn('name', ['Jane Doe', 'John Doe'])->get();
            }

            // Send notification to proper user(s)
            Notification::send($users, new TrafficCreated($traffic));

Thanks for any help you can provide.

1

There are 1 answers

2
brice On BEST ANSWER

You can merge collections together with the merge method.

Something like:

$users = User::whereIn('name', $data['salesman'])->get();

if($data['branch'] === 'Richmond') {
    $branch_users = User::whereIn('name', ['Jane Doe', 'John Doe'])->get();
}

// todo: add other conditions for different branches here

if (isset($branch_users)) {
    $users->merge($branch_users);
}

Notification::send($users, new TrafficCreated($traffic));