Laravel notifications for multi-channel messaging

Carlos Mendez Jan 2026
2 tabs
<?php

namespace App\Notifications;

use App\Models\Post;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;

class PostPublished extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public Post $post
    ) {}

    public function via($notifiable): array
    {
        $channels = ['database'];

        if ($notifiable->notificationPreferences->email) {
            $channels[] = 'mail';
        }

        if ($notifiable->notificationPreferences->sms) {
            $channels[] = 'vonage'; // SMS via Vonage
        }

        return $channels;
    }

    public function toMail($notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('New Post: ' . $this->post->title)
            ->greeting('Hello!')
            ->line($this->post->author->name . ' published a new post.')
            ->action('Read Post', route('posts.show', $this->post))
            ->line('Thank you for being a subscriber!');
    }

    public function toDatabase($notifiable): array
    {
        return [
            'post_id' => $this->post->id,
            'title' => $this->post->title,
            'author' => $this->post->author->name,
            'url' => route('posts.show', $this->post),
        ];
    }

    public function toSlack($notifiable): SlackMessage
    {
        return (new SlackMessage)
            ->content('New post published!')
            ->attachment(function ($attachment) {
                $attachment
                    ->title($this->post->title, route('posts.show', $this->post))
                    ->fields([
                        'Author' => $this->post->author->name,
                        'Published' => $this->post->published_at->diffForHumans(),
                    ]);
            });
    }
}
2 files · php Explain with highlit

Laravel notifications send messages across email, SMS, Slack, database, and more via a unified API. I create notification classes extending Notification with channel-specific methods—toMail(), toDatabase(), toSlack(). The via() method determines which channels to use based on user preferences. Notifications queue automatically with ShouldQueue. Database notifications store in a notifications table for in-app messages. The Notifiable trait on users provides notify() and notifyNow() methods. On-demand notifications send to ad-hoc recipients. Notification events enable logging and analytics. This abstraction makes cross-channel messaging consistent and maintainable without vendor-specific code scattered everywhere.