Brown Daniel
Brown Daniel

Reputation: 1

Laravel daily email send multiple user with schedule

I need to send email to multiple user in every day. My code is like this. It works as well, but I have misunderstood.

foreach($advisors as $advisor) {
    $receivers = [];
    foreach($advisor->clients as $client) {
        array_push($receivers, $client);
    }
    array_push($receivers, $advisor);

    if (count($receivers) > 0) {
        Notification::send($receivers, new DailyEmail($advisor));
    }
}

before I code like below.

foreach($advisors as $advisor) {
    $receivers = [];
    foreach($advisor->clients as $client) {
         array_push($receivers, $client);
    }

    if (count($receivers) > 0) {
         Notification::send($receivers, new DailyEmail($advisor));
    }
    Notification::send($advisor, new DailyEmail($advisor));
}

but if I code like this, only one user got email.

I can't understand, why this works different. If you can explain about this, please.

Upvotes: 0

Views: 173

Answers (1)

Marina Mosti
Marina Mosti

Reputation: 461

The "old" code was firing the Notification::send event twice, once for the receivers and once for the advisor.

Your "new" code only fires it once for the receivers, thus the advisor is not getting an email notification.

Now i may be understanding your code wrong for lack of more information, but if you want to send the notification to the $advisor->clients you dont need to loop them over and make a new array, in fact Notification::send expects a collection

Just do:

foreach($advisors as $advisor) {
    if (count($advisor->clients) > 0) {
        Notification::send($advisor->clients, new DailyEmail($advisor));
    }
}

Upvotes: 0

Related Questions