Make Laravel Notifications Easier to Manage with Notification Events
Imagine a user completes an order.
You want to:
- Send an email
- Store a notification
- Notify the user through another channel
Putting all of that directly inside your controller can quickly become messy.
Laravel Notifications give you a cleaner approach.
Create a Notification
Create one with Artisan:
php artisan make:notification OrderCompleted
Then define the notification:
class OrderCompleted extends Notification
{
public function __construct(public Order $order) {
}
public function via(object $notifiable): array{
return ['mail'];
}
}
Now the notification decides which channel should be used.
Send the Notification
If your User model uses the Notifiable trait:
$user->notify(
new OrderCompleted($order)
);
Your controller doesn't need to know how the notification is delivered.
Add More Channels
You can send the same notification through multiple channels:
public function via(object $notifiable): array
{
return [
'mail',
'database',
];
}
Now the same notification can be delivered through both channels.
Why Is This Useful?
Instead of writing:
Mail::to($user)->send(...);
// Save notification...
// Send another message...
you have one notification:
$user->notify(
new OrderCompleted($order)
);
The notification class owns the delivery details.
When Should You Use Notifications?
They're especially useful for:
- Order updates
- Password changes
- Account activity
- Payment confirmations
- System alerts
- User reminders