Laravel 5.3 - Single Notification File for Different User Collections?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 23:32:13

问题


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'];
}


来源:https://stackoverflow.com/questions/41643939/laravel-5-3-single-notification-file-for-different-user-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!