Laravel provides a powerful, flexible, and elegant notification system that helps you send messages across different channels such as email, SMS, database, broadcast, Slack, and more. Notifications are essential for modern applications that need to alert users about system events such as password resets, new orders, account updates, invoices, reminders, alerts, and confirmations. Instead of writing separate logic for each type of message, Laravel gives developers a unified interface for building and delivering notifications.
This explores Laravel notification channels in depth. You will learn what notification channels are, how Laravel handles them internally, how to create notifications, how to format messages using methods like toMail, toArray, and toBroadcast, and how to send notifications across all default channels. We will also cover database notifications, Slack notifications, Nexmo SMS notifications, broadcast notifications, custom channels, queues, and advanced use cases.
By the end of this article, you will fully understand Laravel’s notification system and how to use it to build scalable alerting and communication features.
Understanding Notification Channels in Laravel
A notification channel defines how a notification is delivered. Every channel provides its own delivery mechanism and formatting logic. Laravel includes several channels by default:
- Mail notifications
- Database notifications
- Broadcast notifications
- Slack notifications
- Nexmo SMS notifications
Each channel uses a specific method inside the notification class:
- toMail
- toArray
- toBroadcast
- toSlack
- toNexmo
Laravel’s notification system is designed to be extensible. You can even create custom channels for WhatsApp, Telegram, Firebase, or any external service.
Why Notification Channels Are Important
Notification channels provide:
- centralization of message formatting
- separation of concerns
- consistency across different channels
- reusability
- integration with queues
- extensibility
- better maintainability
Instead of writing separate code for sending emails, writing to the database, and sending SMS, you write a single notification class that supports multiple channels.
Laravel automatically selects the right channel based on the method’s return value from the via method.
Creating a Notification in Laravel
Create a notification using Artisan:
php artisan make:notification OrderShipped
This generates:
app/Notifications/OrderShipped.php
Inside this class, you define:
- which channels the notification will use
- how the message should be formatted for each channel
Basic template:
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Order Shipped')
->line('Your order has been shipped.')
->action('Track Order', url('/orders'));
}
Sending Notifications
You can send notifications to any model that uses the Notifiable trait.
Example:
$user->notify(new OrderShipped($order));
Or using Notification facade:
Notification::send($users, new OrderShipped($order));
Notifications can target:
- users
- admins
- customers
- mobile numbers
- Slack channels
Defining Channels Using the via Method
The via method returns a list of channels.
Example:
public function via($notifiable)
{
return ['mail', 'database', 'slack'];
}
Laravel determines which methods to use:
- toMail
- toArray
- toSlack
You only include methods for channels you use.
Mail Notification Channel
Mail notifications are sent using the toMail method.
Mail is the most commonly used notification method.
Example:
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Order Confirmation')
->greeting('Hello!')
->line('Your order has been placed.')
->action('View Order', url('/orders'))
->line('Thank you for shopping with us.');
}
MailMessage supports:
- subject
- greeting
- line
- action
- markdown
Markdown emails provide advanced formatting:
php artisan make:mail OrderMail --markdown=emails.order
Mail notifications integrate smoothly with queues.
Database Notification Channel
Database notifications store data inside the notifications table.
Create the table:
php artisan notifications:table
php artisan migrate
Define a database notification:
public function toArray($notifiable)
{
return [
'order_id' => $this->order->id,
'status' => 'shipped',
'message' => 'Your order has been shipped.'
];
}
View database notifications:
$user->notifications;
Unread notifications:
$user->unreadNotifications;
Mark notification as read:
$notification->markAsRead();
Delete:
$notification->delete();
Database notifications are ideal for user dashboards.
Broadcast Notification Channel
Broadcast notifications use Laravel Echo and WebSockets to deliver real-time alerts.
Add broadcast to via:
public function via($notifiable)
{
return ['broadcast'];
}
Define broadcast structure:
public function toBroadcast($notifiable)
{
return new BroadcastMessage([
'order_id' => $this->order->id,
'status' => 'shipped'
]);
}
Broadcast configuration:
BROADCAST_DRIVER=pusher
Or custom WebSockets using Laravel WebSockets package.
Frontend with Echo:
Echo.private('users.' + userId)
.notification((notification) => {
console.log(notification);
});
Broadcast notifications are used for:
- real-time chat
- order updates
- admin alerts
- stock updates
- live dashboards
Slack Notification Channel
Slack allows sending notifications to Slack channels using webhooks.
Add Slack to via:
public function via($notifiable)
{
return ['slack'];
}
Slack message:
public function toSlack($notifiable)
{
return (new SlackMessage)
->content('A new order has been placed!');
}
Advanced formatting:
return (new SlackMessage)
->attachment(function ($attachment) {
$attachment->title('Order Details')
->fields([
'Order ID' => $this->order->id,
'Status' => 'Shipped'
]);
});
Slack notifications are widely used for internal alerts.
Nexmo SMS Notification Channel
Nexmo (now Vonage) sends SMS notifications.
Set channel:
public function via($notifiable)
{
return ['nexmo'];
}
SMS message:
public function toNexmo($notifiable)
{
return (new NexmoMessage)
->content('Your order has been shipped.');
}
Define routing:
public function routeNotificationForNexmo()
{
return $this->phone_number;
}
SMS notifications are useful for:
- OTP verification
- order delivery alerts
- security alerts
- marketing messages
Customizing Channels Based on Conditions
You can return different channels dynamically:
public function via($notifiable)
{
if ($notifiable->prefers_sms) {
return ['nexmo'];
}
return ['mail'];
}
Example:
- premium users get SMS
- normal users get email
Custom Notification Channels
You can create your own channels for:
- Telegram
- Firebase Push
- Slack Bot API
- Discord
Create custom channel:
php artisan make:notification-channel WhatsAppChannel
Channel structure:
public function send($notifiable, Notification $notification)
{
$message = $notification->toWhatsApp($notifiable);
// send to API
}
Notification method:
public function toWhatsApp($notifiable)
{
return "Your order is ready.";
}
Queuing Notifications for Better Performance
Notifications can be queued automatically.
Add ShouldQueue:
class OrderShipped extends Notification implements ShouldQueue
{
}
Or define in config:
'queue' => 'notifications'
Queued notifications reduce delays in user experience.
Routing Notifications to Different Destinations
Route dynamically:
public function routeNotificationForMail()
{
return $this->business_email;
}
SMS routing:
public function routeNotificationForNexmo()
{
return $this->mobile;
}
Slack routing:
public function routeNotificationForSlack()
{
return $this->slack_webhook_url;
}
Allows notification per user or per situation.
Notification Facade vs Notifiable Trait
Two ways to send notifications:
Using model:
$user->notify(new OrderShipped);
Using Notification facade:
Notification::send($users, new OrderShipped);
Notification facade is ideal for broadcasting to multiple users.
Using Notifications in API Development
API controllers send notifications for:
- successful payments
- order confirmations
- OTP codes
- event reminders
- account warnings
Return API response:
return response()->json(['message' => 'Notification sent']);
Accessing Notification Data
Read stored notifications:
foreach ($user->notifications as $notification) {
echo $notification->data['status'];
}
Unread count:
$user->unreadNotifications->count();
Mark all as read:
$user->unreadNotifications->markAsRead();
Notification Events
Laravel fires two events:
Illuminate\Notifications\Events\NotificationSent
Illuminate\Notifications\Events\NotificationFailed
Listen to events:
php artisan make:listener LogNotification
Attach to EventServiceProvider.
Testing Notifications
Laravel provides testing helpers.
Fake notifications:
Notification::fake();
Assert sent:
Notification::assertSentTo($user, OrderShipped::class);
Assert not sent:
Notification::assertNothingSent();
Real-World Use Cases for Each Channel
Mail:
- receipts
- confirmations
- password resets
Database:
- dashboard alerts
- system messages
- admin approvals
Broadcast:
- chat messages
- live updates
- notification counters
Slack:
- server alerts
- payment updates
- error logging
Nexmo SMS:
- OTP codes
- delivery alerts
- emergency notices
Best Practices for Using Notification Channels
- always queue notifications
- use database notifications for dashboard alerts
- use broadcast for real-time features
- avoid sending sensitive info over email or SMS
- use proper rate-limiting
- log failures
- keep notification classes small
- isolate channel-specific logic
Leave a Reply