clover
clover

Reputation: 45

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());

Upvotes: 1

Views: 484

Answers (1)

Ahrengot
Ahrengot

Reputation: 1589

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

Upvotes: 1

Related Questions