Search code examples
laravellaravel-9

How to send notification through only one channel - Laravel 9


I need to send notifications to users using Web Push and e-mail, but in some cases it may turn out that the user does not have an e-mail address, so then only using Web Push. Is it possible to choose which channel the notification should be sent through, or do I have to create separate notifications for both channels and trigger the e-mail notification only if the user has an assigned address?

Methods in notifications:

public function via($notifiable)
{
    return [
        MailChannel::class,
        WebPushChannel::class,
    ];
}


public function toWebPush($notifiable, $notification)
{
    return (new WebPushMessage)
        ->title('Twój profil jest aktywny')
        ->body('Administrator aktywował Twoje konto')
        ->data([
            'type' => class_basename($this),
        ])
        ->options(['TTL' => 1000]);
}

public function toMail($notifiable)
{
    return (new MailMessage)
        ->subject('Title..')
        ->line("Content...")
}

Sending notifications:

$user->notify(new UserActivation());

Solution

  • That's what the via method is for. Check for the $notifiable->email there and return the appropriate channel(s)