What are notifications?
Notifications are short, informational messages sent to users when something happens in your application—an invoice is paid, a password is reset, a deployment completes. Unlike mailables, a single notification class can deliver its message across multiple channels. The sameInvoicePaid notification can send an email and save a database record simultaneously.
Generating notifications
Create a notification with Artisan:app/Notifications/InvoicePaid.php.
Sending notifications
Via the notifiable trait
TheApp\Models\User model includes the Notifiable trait by default, which exposes a notify method:
Notifiable to any model, not just User.
Via the Notification facade
Send to multiple users at once using theNotification facade:
Specifying delivery channels
Every notification class has avia method that returns which channels to use:
| Channel | Description |
|---|---|
mail | Send via email |
database | Store in the database for in-app display |
broadcast | Broadcast over WebSockets |
vonage | Send SMS via Vonage |
slack | Send to a Slack channel |
Mail notifications
Define atoMail method on the notification to format the email:
Markdown mail notifications
Generate a notification with a Markdown template for full HTML control:markdown instead of chaining MailMessage methods:
Database notifications
Store notifications in a database table and display them in your UI.Setup
Create thenotifications table:
database to the via method, then define a toDatabase (or toArray) method returning an array of data:
Reading notifications
Access a user’s notifications through thenotifications relationship:
Queueing notifications
Notifications that call external services should be queued. AddShouldQueue and Queueable:
$user->notify(new InvoicePaid($invoice)) queues the notification automatically.
Delaying delivery
On-demand notifications
Send a notification to a recipient who isn’t stored in your database:Slack notifications
Define atoSlack method after connecting a Slack app to your workspace:
A complete example
Testing notifications
UseNotification::fake() to assert notifications are sent without actually delivering them:
- Pest
- PHPUnit
Learn how to build rich HTML email templates with mailable classes and Markdown components.