patternphplaravelTip
Laravel Notifications: Choosing the Right Channel
Viewed 0 times
notificationviatoMaildatabase channelShouldQueueon-demandNotifiablemulti-channel
Problem
Notification logic is scattered across controllers and event listeners. Sending via multiple channels (email + SMS) requires duplicating delivery logic.
Solution
Generate notifications with php artisan make:notification. Implement via() to return an array of channels based on the notifiable's preferences. Each channel method (toMail, toSms, toBroadcast) builds the message independently. Queue notifications with ShouldQueue on the notification class.
Why
The Notification system provides a unified interface for multi-channel delivery. The Notifiable trait on User provides notify(). Queuing moves delivery off the request cycle.
Gotchas
- On-demand notifications for non-model recipients use Notification::route('mail', 'email@example.com')->notify(new MyNotification())
- The database channel stores notifications in a notifications table—run php artisan notifications:table first
- toMail() must return a MailMessage or Mailable instance
- ShouldQueue on the notification class queues each channel separately as independent jobs
Code Snippets
Multi-channel notification
class OrderShipped extends Notification implements ShouldQueue
{
public function via(object $notifiable): array
{
return $notifiable->prefers_sms
? ['vonage', 'database']
: ['mail', 'database'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)->subject('Shipped')->line('Your order is on the way.');
}
}Revisions (0)
No revisions yet.