Skip to main content

Email and Multi-Channel Notifications

23/28
Chapter 6 Queues, Events, and Notifications

Email and Multi-Channel Notifications

20 min read Lesson 23 / 28

Notifications Across Multiple Channels

Laravel Notifications send brief messages via email, SMS, Slack, database, and custom channels from a single class.

Creating a Notification

php artisan make:notification OrderShippedNotification
class OrderShippedNotification extends Notification implements ShouldQueue
{
    public function __construct(public Order $order) {}

    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('Your order has shipped!')
            ->greeting("Hi {$notifiable->name}!")
            ->line("Order #{$this->order->id} is on its way.")
            ->action('Track Order', route('orders.show', $this->order))
            ->line('Thank you for your purchase.');
    }

    public function toArray(object $notifiable): array
    {
        return [
            'order_id' => $this->order->id,
            'message' => "Order #{$this->order->id} has shipped.",
        ];
    }
}

Sending Notifications

$user->notify(new OrderShippedNotification($order));

// To non-users
Notification::route('mail', 'manager@example.com')
    ->notify(new OrderShippedNotification($order));

Database Notifications

php artisan notifications:table
php artisan migrate

Display in your UI:

// In controller
$notifications = auth()->user()->unreadNotifications;

// Mark as read
auth()->user()->unreadNotifications->markAsRead();

Custom Mailables

For rich, branded emails:

php artisan make:mail WelcomeMail --markdown=emails.welcome
class WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(public User $user) {}

    public function content(): Content
    {
        return new Content(markdown: 'emails.welcome');
    }
}
Mail::to($user)->queue(new WelcomeMail($user));