Laravel 5.3 - Single Notification File for Differe

2019-07-25 09:22发布

问题:

Given 100 followers, once I complete a todo, a notification is fired. The issue is 80 of them want email only notification, the other 20 want sms only notification. Does that mean I need to use 2 different notification calls like this:

Notification::send($emailOnlyUsers, new TodoCompletedEmail($todo));

which has only the mail channel, and then:

Notification::send($smsOnlyUsers, new TodoCompletedSms($todo));

which has only the sms channel? Or is it possible to have the logic of $emailOnlyUsers and $smsOnlyUsers in the TodoCompleted Notification file where both channels are listed together to handle the different channels for different users in one file? Something like this:

$user->notify(new TodoCompletedEmail($todo));

I ask because I would rather do it in one file with different channels, but I don't think I can since Laravel's Notification expects a passed collection of users (in this situation there are really 2 user collections), but more channels/different collections are possible and it would suck to have to create a new notification file for each channel/user collection for the same TodoCompleted notification. Can someone shed some light on whether it is possible to have it in a single file and if so how?

回答1:

What about something like this?

foreach($users as $user)
    $user->notify(new TodoCompleted($todo));

Then in your TodoCompleted Class

private $todo;

/**
 * Create a new notification instance.
 *
 * @param $todo
 */
public function __construct($todo)
{
    $this->todo = $todo;
}

/**
 * Get the notification's delivery channels.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function via($notifiable)
{
    // Change "prefer_sms" to whatever logic you're using to determine if the user should be sent sms or email.
    if($notifiable->prefers_sms)
        return ['sms', 'database'];

    return ['mail', 'database'];
}