Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 67 ยท Queues, Events and Notifications

Notifications

Send one message through many channels with Laravel notifications: via(), mail, database, Slack and broadcast channels, queued delivery and testing.

An invoice is overdue. A comment was posted on your article. A deploy finished. Each of these is a short message for one person, and the best channel depends on the person: an email for one, an in-app bell icon for another, a Slack message for the team. Writing separate code for every channel quickly turns into a mess.

Laravel notifications give you one class per message and a list of channels to deliver it through. The notification says what to tell the user and how for each channel; Laravel does the delivering. Where mail sends one kind of message, notifications sit on top and can include mail as one channel among several.

Laravel cannot run on this site, so Laravel code blocks are read-only. The runnable examples are plain PHP stand-ins for the same design, and each section says which is which.

The shape of a notification

flowchart LR
    U["User<br/>(Notifiable)"] -->|"notify(new InvoicePaid)"| N[Notification]
    N -->|"via()"| V{"Which channels?"}
    V --> M["toMail()"]
    V --> D["toDatabase()"]
    V --> S["toSlack()"]
    V --> B["toBroadcast()"]
    M --> MC[Mail channel]
    D --> DC[Database channel]
    S --> SC[Slack channel]
    B --> BC[Broadcast channel]

via() chooses the channels, and each channel calls its own toX() method to build its version of the message.

Generate one with Artisan:

Terminal
php artisan make:notification InvoicePaid
PHP
<?php

namespace App\Notifications;

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

class InvoicePaid extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(public Invoice $invoice)
    {
    }

    /** @return list<string> */
    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject("Invoice {$this->invoice->number} paid")
            ->greeting("Hello {$notifiable->name},")
            ->line('We received your payment. Thank you.')
            ->action('View invoice', url("/invoices/{$this->invoice->id}"))
            ->line('Have a great day!');
    }

    /** @return array<string, mixed> */
    public function toArray(object $notifiable): array
    {
        return [
            'invoice_id' => $this->invoice->id,
            'amount' => $this->invoice->total,
        ];
    }
}

Sending it is a method call on any model that uses the Notifiable trait. The User model has it by default:

PHP
$user->notify(new InvoicePaid($invoice));

use Illuminate\Support\Facades\Notification;

Notification::send($team->members, new InvoicePaid($invoice));
Notification::route('mail', '[email protected]')->notify(new InvoicePaid($invoice));

The last line is an on-demand notification: it goes to an address that does not belong to a user model.

via() and per-user preferences

via() receives the notifiable, so it can decide per user. This is the natural place for notification preferences:

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

    if ($notifiable->prefers_email) {
        $channels[] = 'mail';
    }
    if ($notifiable->slack_webhook_url !== null) {
        $channels[] = 'slack';
    }

    return $channels;
}

Each channel also needs to know where to send. The mail channel reads $user->email by default, and you can override it with a routeNotificationForMail() method on the model. Other channels use similar routeNotificationFor... methods.

Built-in channels

  • mail: builds a message with toMail(), using the same mailer and the same Markdown templates as mailables. The fluent MailMessage is enough for most notifications, and it can also return a full mailable.
  • database: stores a row in the notifications table, with the data from toArray() (or toDatabase()). It powers the in-app notification list. Create the table with php artisan make:notifications-table, then migrate.
  • broadcast: pushes the data to a browser over WebSockets, so a bell icon can update live. See broadcasting and Reverb.
  • slack: posts to Slack with toSlack(). It comes from the first-party laravel/slack-notification-channel package (install it with Composer) and needs a Slack app token or webhook configured in config/services.php.
  • Community channels cover SMS (the first-party Vonage package, and others), Telegram, push notifications and more at the same level of effort: you add via() and a toX() method.

Database notifications

The notifications table is polymorphic, so one table serves every model. Reading them is a relationship on the notifiable:

PHP
$user->unreadNotifications;            // collection
$user->notifications()->latest()->take(10)->get();

foreach ($user->unreadNotifications as $notification) {
    echo $notification->data['invoice_id'];
}

$user->unreadNotifications->markAsRead();
$notification->markAsRead();

The data column is JSON, and $notification->type holds the class name. Keep the stored data small and self-contained: store IDs and a few display fields, because you cannot always rebuild the original model later (it may have been deleted). Also design the data so that old rows still make sense after you rename or change a notification class.

Queued notifications

Sending an email or calling Slack is slow, so implement ShouldQueue on the notification, as above, and Laravel queues one job per channel. Failing to reach Slack does not prevent the email from going out. You can route channels to different queues:

PHP
public function viaQueues(): array
{
    return [
        'mail' => 'mail-queue',
        'slack' => 'slack-queue',
    ];
}

If the notification is sent inside a database transaction, set public $afterCommit = true; so the worker never runs before the data exists.

A multi-channel notification stand-in

Here is a plain-PHP model of the design. Each notification declares channels in via() and offers a toX() method per channel; a tiny manager looks them up and calls the matching channel. Real Laravel adds queues, translation and events around this core.

PHP Notification channels stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Grace turned email off, so her via() returns only database, which is exactly how preferences work in Laravel.

Marking notifications read: the data layer

The database channel boils down to a table with a JSON column and a nullable read_at timestamp. This example builds that table in SQLite and shows the unread query, the way unreadNotifications and markAsRead() work conceptually:

PHP A notifications table with read state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Testing notifications

PHP
use App\Notifications\InvoicePaid;
use Illuminate\Support\Facades\Notification;

it('notifies the customer when an invoice is paid', function () {
    Notification::fake();

    $user = User::factory()->create();
    $invoice = Invoice::factory()->for($user)->create();

    $this->post("/invoices/{$invoice->id}/pay");

    Notification::assertSentTo($user, InvoicePaid::class, function ($notification, $channels) {
        return in_array('mail', $channels);
    });
    Notification::assertNothingSentTo(User::factory()->create());
});

Notification::fake() records notifications without delivering them, like the other fakes covered in faking and mocking. To test the rendered content, call $notification->toMail($user) directly and assert on the returned object.

When to use which tool

Use a mailable when you are sending an email that is specific to mail, such as a newsletter with a complex layout. Use a notification when the same information may reach the user in several ways, or when you want an in-app list. Use an event to announce that something happened, and let a listener send the notification, so the business code stays free of messaging details.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the via() method of a notification return?

    via() receives the notifiable and returns the channels to use. Each channel then calls its own toX() method, for example toMail() or toArray().
  2. 2. Where do database notifications live, and how do you list a user's unread ones?

    The database channel writes rows to the notifications table, and the Notifiable trait gives you notifications and unreadNotifications relationships.
  3. 3. How do you let each user choose whether they get a notification by email?

    via() gets the notifiable object, so it can include or exclude channels according to user settings.
  4. 4. What is the benefit of implementing ShouldQueue on a notification?

    Queued notifications are delivered by workers, one job per channel, with the usual retries. The request returns immediately.

Summary

  • A notification is one class that describes a message for one or more channels; via() picks them, and toMail(), toArray(), toSlack() build each version.
  • Call $user->notify() on a Notifiable model, or Notification::send() for many recipients; use on-demand routes for addresses without a model.
  • The database channel stores JSON in the notifications table with read_at, and exposes unreadNotifications.
  • Implement ShouldQueue to deliver through workers; use afterCommit inside transactions.
  • Use Notification::fake() in tests.

Next: Task Scheduling