Laravel Notifications provide a flexible, expressive, and unified way to send alerts or updates to users through a variety of channels. Whether you want to send an email, store a notification in the database, deliver an SMS message, notify a user through Slack, or broadcast a real-time update across the frontend, the Laravel Notification system handles these tasks with ease. This elegant feature simplifies the otherwise complex logic of multi-channel communication while ensuring consistency, maintainability, and scalability across your application. In this article, we will explore what Notifications are, how they work, how to send them through different channels, and how to structure them for large applications.
What Notifications Are in Laravel
Notifications in Laravel are lightweight messages sent to users to inform them about important events. These messages can be delivered through multiple channels such as:
- SMS
- Database
- Slack
- Broadcast
- Vonage (formerly Nexmo)
- Custom channels
Notifications are user-friendly, customizable, and designed to integrate seamlessly with the rest of Laravel’s ecosystem.
Why Notifications Matter in Modern Applications
Notifications are more than simple messages. They help maintain engagement, communicate important events, and enhance the user experience. For example:
- Sending order confirmations
- Appointing reminders
- Notifying users of new messages
- Sending invoice receipts
- Alerting admins about suspicious activity
- Confirming password resets
- Broadcasting real-time system updates
Notifications ensure your users never miss important information.
Creating a Notification
Laravel provides an Artisan command to generate notification classes:
php artisan make:notification InvoicePaid
This creates a file in:
app/Notifications/InvoicePaid.php
Each notification class contains methods that determine how the notification will be delivered across various channels.
Anatomy of a Notification Class
A typical notification class includes:
- The
via()method - Channel methods such as
toMail(),toDatabase(), etc. - Optional helper methods
- Data passed in through the constructor
Example:
class InvoicePaid extends Notification
{
private $invoice;
public function __construct($invoice)
{
$this->invoice = $invoice;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Invoice Paid')
->line('Your invoice has been paid.')
->action('View Invoice', url('/invoice/'.$this->invoice->id));
}
}
This notification will send an email with a message containing invoice details.
Sending a Notification
Sending a notification is simple:
$user->notify(new InvoicePaid($invoice));
Laravel automatically determines:
- Which channels to use
- Which contact data to use (email, phone, Slack ID, etc.)
- How to format the notification
This keeps your application logic clean and expressive.
Notifiable Trait
The Notifiable trait must be used in any model that will receive notifications. This trait provides the notify() method.
Users typically include it:
class User extends Authenticatable
{
use Notifiable;
}
Once a model uses this trait, it can receive notifications across all registered channels.
Notification Channels
Laravel supports multiple notification channels. Developers can choose one or many channels per notification depending on the situation.
Email Notifications
Email is the most commonly used notification channel. Laravel makes creating beautiful mail messages simple.
In the via() method:
return ['mail'];
And the message is structured using toMail().
Advantages of email notifications:
- Fully customizable
- Integrates with Markdown mail templates
- Supports attachments
- Works with any supported mail provider
SMS Notifications Using Vonage
Laravel integrates with SMS providers like Vonage. To send SMS:
In the via() method:
return ['vonage'];
Define SMS content:
public function toVonage($notifiable)
{
return (new VonageMessage)
->content('Your invoice has been paid.');
}
SMS notifications are ideal for urgent or high-priority messages.
Slack Notifications
Slack notifications integrate with team environments for real-time communication.
Define Slack channel:
return ['slack'];
Define Slack message:
public function toSlack($notifiable)
{
return (new SlackMessage)
->content('A new invoice has been paid!');
}
Slack notifications are useful for operations teams, admin alerts, or system monitoring.
Database Notifications
Database notifications store messages in a table instead of sending them externally.
In the via() method:
return ['database'];
Define database content:
public function toDatabase($notifiable)
{
return [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
];
}
Database notifications appear in:
notifications table
This allows building notification panels inside dashboards.
Broadcast Notifications
Broadcast notifications are ideal for real-time updates using WebSockets.
In via():
return ['broadcast'];
Define structure:
public function toBroadcast($notifiable)
{
return new BroadcastMessage([
'invoice_id' => $this->invoice->id,
'paid_at' => now(),
]);
}
These updates can be received instantly by frontend applications using:
- Laravel Echo
- Pusher
- WebSockets
Ideal for real-time dashboards, chat systems, and live notifications.
Array Notifications
Array format is used when the notification needs to be converted into JSON.
public function toArray($notifiable)
{
return [
'invoice_id' => $this->invoice->id,
'message' => 'Invoice paid successfully.',
];
}
Useful for API responses and custom serialization.
Sending Notifications to Multiple Channels
You can send the same notification through several channels at once.
Example:
public function via($notifiable)
{
return ['mail', 'database', 'slack'];
}
This approach ensures that important messages reach users through every available medium.
On-Demand Notifications
Sometimes, you want to send notifications to recipients who do not have a user account. Laravel supports on-demand notifications.
Example:
Notification::route('mail', '[email protected]')
->notify(new InvoicePaid($invoice));
Or for SMS:
Notification::route('vonage', '1234567890')
->notify(new InvoicePaid($invoice));
This avoids creating unnecessary user accounts.
Custom Notification Channels
Laravel lets you create your own channels if needed.
For example:
- Telegram
- Push notifications
- REST API webhooks
- IoT device triggers
Creating custom channels allows major flexibility in communication workflows.
Broadcasting Notifications in Real Time
To broadcast, you configure a broadcast driver such as:
- Pusher
- Redis
- Socket.io
- Laravel WebSockets
When a notification is broadcast, the frontend can listen in real time using Laravel Echo.
Example:
Echo.private('App.Models.User.' + userId)
.notification((notification) => {
console.log(notification);
});
This creates a dynamic user experience where notifications appear instantly without page reloads.
Storing Notifications in the Database
Laravel includes a built-in migration for storing notifications.
Run:
php artisan notifications:table
Then migrate:
php artisan migrate
Now database notifications are stored in the notifications table.
Retrieving Database Notifications
Access a user’s notifications with:
$user->notifications;
Unread notifications:
$user->unreadNotifications;
Mark notification as read:
$notification->markAsRead();
Mark all unread notifications as read:
$user->unreadNotifications->markAsRead();
This is useful for dashboards and notification centers.
Formatting Notification Data
You can structure data in the resource-like format.
Example:
return [
'title' => 'Invoice Paid',
'details' => [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount
],
'timestamp' => now()
];
This allows clean display on the frontend.
Using Markdown Mail Templates
For email notifications, Laravel supports Markdown templates.
Create a template:
php artisan make:mail InvoiceMail --markdown=emails.invoice
In your notification:
return (new MailMessage)
->markdown('emails.invoice', ['invoice' => $this->invoice]);
Markdown mail greatly improves email formatting.
Adding Attachments to Notifications
To attach files in emails:
return (new MailMessage)
->line('Your invoice is attached.')
->attach(storage_path('invoices/'.$this->invoice->file));
Useful for:
- PDF invoices
- Reports
- Downloadable resources
Notification Queues
Notifications can be queued for better performance.
Add:
implements ShouldQueue
To your notification class.
This tells Laravel to send the notification asynchronously in the background.
Useful for:
- Large email campaigns
- High-traffic systems
- Bulk alerts
Localizing Notifications
Laravel supports translation for notifications.
Inside toMail():
return (new MailMessage)
->subject(__('Invoice Paid'))
->line(__('Your invoice has been paid.'));
This enables multi-language support across your application.
Customizing Routing for Notifications
You can define routing logic inside the notifiable model:
public function routeNotificationForMail()
{
return $this->email_address;
}
Or for Slack:
public function routeNotificationForSlack()
{
return $this->slack_webhook;
}
This adds flexibility in how users receive notifications.
Filtering Notifications
You can choose to send a notification only under certain conditions.
Example:
if ($user->settings->notify_invoice_paid) {
$user->notify(new InvoicePaid($invoice));
}
This respects user preferences and avoids unnecessary communication.
Event-Driven Notifications
Laravel events can trigger notifications.
Example event:
- OrderShipped
Listener:
- SendOrderShippedNotification
This creates a loosely coupled architecture.
Notification Testing
Laravel makes testing straightforward.
Example:
Notification::fake();
$user->notify(new InvoicePaid($invoice));
Notification::assertSentTo(
[$user], InvoicePaid::class
);
Testing notifications ensures reliability across channels.
Building Notification Centers
Database notifications make it easy to build a notification panel inside your app.
Example:
- Show unread notifications
- Display notification history
- Create a dropdown notification feed
- Allow marking notifications as read
This enhances your application’s user experience.
Real-World Use Cases for Notifications
Notifications are used across many industries:
- E-commerce order updates
- SaaS subscription alerts
- Financial transaction confirmations
- Appointment reminders
- Delivery status updates
- Internal team alerts
- Security warnings
- System failure alerts
Notifications improve engagement and reliability.
Common Mistakes When Using Notifications
Common mistakes include:
- Sending too many notifications
- Not using queues
- Not separating concerns
- Ignoring unread count logic
- Overusing email for simple alerts
- Not storing notifications in the database
- Forgetting to register channels
Avoiding these helps deliver a clean notification system.
Structuring Notifications in Large Applications
Organizing notifications becomes important as systems grow.
Recommended structure:
app/Notifications
User
ProfileUpdated.php
PasswordReset.php
Orders
OrderShipped.php
InvoicePaid.php
Admin
SystemAlert.php
This keeps notifications grouped by domain.
Future-Proofing Your Notification System
To ensure long-term scalability:
- Use queues
- Support multiple channels
- Allow user preferences
- Build settings for opt-in/out
- Use versioning for API-driven notifications
- Store all exceptions with logs
Leave a Reply