Notifications
- Introduction
- Writing notifications
- Notifiables
- Sending notifications
- Choosing channels for each notifiable
- Package channels
- Testing
Introduction
When a customer pays an invoice, you might email them, send a text message, and post the payment to their team's Slack channel. A notification describes that event once and builds a message for each channel, and Laravel delivers those messages to every user or team you specify.
Laravel delivers notifications over email, SMS, Slack, and custom package channels such as Discord. Email uses mail and text messages use SMS, inheriting the configuration and queues from those guides, so configure each channel you plan to use first.
Keep notifications short and informational. To send one email with its own layout and attachments, such as an order receipt, send a mailable directly.
Writing notifications
Each notification is a struct holding the data its messages need, paired with an impl block annotated with #[notification]. Define a mail, sms, or slack method for each channel the notification supports, typically in a module such as src/notifications.rs.
For example, suppose your application has an Invoice model and an InvoicePaidEmail mailable. This notification alerts a user when their invoice is paid:
1use laravel::mail::Mailable;2use laravel::notification;34use crate::mail::InvoicePaidEmail;56pub struct InvoicePaid {7 pub invoice: Invoice,8}910#[notification]11impl InvoicePaid {12 fn mail(&self, user: &User) -> impl Mailable {13 InvoicePaidEmail { name: user.name.clone(), invoice_id: self.invoice.id }14 }1516 fn sms(&self, _user: &User) -> String {17 format!("Invoice #{} is paid. Thanks!", self.invoice.id)18 }19}1use laravel::mail::Mailable;2use laravel::notification;34use crate::mail::InvoicePaidEmail;56pub struct InvoicePaid {7 pub invoice: Invoice,8}910#[notification]11impl InvoicePaid {12 fn mail(&self, user: &User) -> impl Mailable {13 InvoicePaidEmail { name: user.name.clone(), invoice_id: self.invoice.id }14 }1516 fn sms(&self, _user: &User) -> String {17 format!("Invoice #{} is paid. Thanks!", self.invoice.id)18 }19}
Each method's second argument is the notifiable that receives the message, here a &User. Every method in one impl takes the same notifiable type. To send the notification to teams too, write a second #[notification] impl whose methods take &Team, as the Slack example does.
Channel methods are synchronous, so load any related models or data you need before sending the notification. Because Laravel calls these methods in the handler or job that dispatches the notification, route URLs, configuration, and context values are available directly. If a channel method can fail (such as when generating a route URL), return a laravel::Result instead; any error aborts the send before any messages are delivered.
A notification owns its data, as a mailable does, so the fake can keep it for your tests. When you still need a value after sending, clone it into the notification, as in InvoicePaid { invoice: invoice.clone() }.
Mail messages
mail returns the email one notifiable receives. It may be a derived mailable, a mailable that builds its message itself, or a Message. InvoicePaidEmail is a derived mailable, which renders resources/views/mail/invoice-paid-email.html with its name and invoice_id:
1use laravel::mail::Mailable;23#[derive(Mailable)]4#[mail(subject = "Invoice #{invoice_id} is paid")]5pub struct InvoicePaidEmail {6 pub name: String,7 pub invoice_id: i64,8}1use laravel::mail::Mailable;23#[derive(Mailable)]4#[mail(subject = "Invoice #{invoice_id} is paid")]5pub struct InvoicePaidEmail {6 pub name: String,7 pub invoice_id: i64,8}
Laravel automatically attaches the notifiable's email address as the recipient, so the mailable does not need to specify to. To learn more about views, subjects, and attachments, check out the Mail guide.
SMS messages
sms returns the text as a String or a &str, which goes out from your SMS_FROM number. To send from another number, return an sms::Message instead:
1use laravel::sms;23fn sms(&self, _user: &User) -> sms::Message {4 sms::Message::new(format!("Invoice #{} is paid.", self.invoice.id)).from("+15555550199")5}1use laravel::sms;23fn sms(&self, _user: &User) -> sms::Message {4 sms::Message::new(format!("Invoice #{} is paid.", self.invoice.id)).from("+15555550199")5}
Slack messages
slack returns a slack::Message, with blocks such as sections and buttons. Slack messages usually go to a team's channel rather than to one user. For example, suppose your application has a Team model with a slack_channel_id column:
1use laravel::notification;2use laravel::prelude::*;3use laravel::slack::{Button, Message, Section};45#[notification]6impl InvoicePaid {7 fn slack(&self, _team: &Team) -> laravel::Result<Message> {8 let url = route!(invoices::show, &self.invoice)?;9 let amount = format!("${:.2}", self.invoice.total as f64 / 100.0);1011 Ok(Message::new(format!("Invoice #{} is paid", self.invoice.id))12 .section(Section::new("Invoice paid.").field("Amount", amount))13 .actions([Button::link("View invoice", url)]))14 }15}1use laravel::notification;2use laravel::prelude::*;3use laravel::slack::{Button, Message, Section};45#[notification]6impl InvoicePaid {7 fn slack(&self, _team: &Team) -> laravel::Result<Message> {8 let url = route!(invoices::show, &self.invoice)?;9 let amount = format!("${:.2}", self.invoice.total as f64 / 100.0);1011 Ok(Message::new(format!("Invoice #{} is paid", self.invoice.id))12 .section(Section::new("Invoice paid.").field("Amount", amount))13 .actions([Button::link("View invoice", url)]))14 }15}
The message goes to the team's Slack route. To set up your Slack app and handle button clicks, check out the Slack guide.
Notifiables
A notifiable is a type that receives notifications, such as User or Team. For each channel it supports, implement ReceivesMail, ReceivesSms, or ReceivesSlack to provide its email address, phone number, or Slack route. Suppose your users table has a nullable phone column:
1use laravel::mail::Address;2use laravel::notification::{ReceivesMail, ReceivesSlack, ReceivesSms};3use laravel::slack::Route;4use laravel::sms::PhoneNumber;56impl ReceivesMail for User {7 fn mail_address(&self) -> Option<Address> {8 Some(Address::new(&self.email).with_name(&self.name))9 }10}1112impl ReceivesSms for User {13 fn sms_number(&self) -> Option<PhoneNumber> {14 self.phone.as_deref().map(PhoneNumber::new)15 }16}1718impl ReceivesSlack for Team {19 fn slack_route(&self) -> Option<Route> {20 self.slack_channel_id.as_deref().map(Route::channel)21 }22}1use laravel::mail::Address;2use laravel::notification::{ReceivesMail, ReceivesSlack, ReceivesSms};3use laravel::slack::Route;4use laravel::sms::PhoneNumber;56impl ReceivesMail for User {7 fn mail_address(&self) -> Option<Address> {8 Some(Address::new(&self.email).with_name(&self.name))9 }10}1112impl ReceivesSms for User {13 fn sms_number(&self) -> Option<PhoneNumber> {14 self.phone.as_deref().map(PhoneNumber::new)15 }16}1718impl ReceivesSlack for Team {19 fn slack_route(&self) -> Option<Route> {20 self.slack_channel_id.as_deref().map(Route::channel)21 }22}
When one of these methods returns None, the send skips that channel for that notifiable without an error. A user who signed up without a phone number still gets the email.
A notifiable needs an implementation for every channel its notifications build. Sending InvoicePaid to a type without ReceivesSms doesn't compile.
Sending notifications
To send a notification, specify its recipients with notification::to, then call queue or send. Most handlers should queue notifications so HTTP responses don't wait on external providers. This handler charges an invoice and notifies the customer:
1use laravel::notification;2use laravel::prelude::*;34use crate::models::Invoice;5use crate::notifications::InvoicePaid;67pub async fn pay(Params(id): Params<i64>) -> laravel::Result<Redirect> {8 let invoice = Invoice::query()9 .with(Invoice::user)10 .find_or_fail(id)11 .await?;1213 // Charge the invoice...1415 notification::to(&invoice.user)16 .queue(InvoicePaid { invoice: invoice.clone() })17 .await?;1819 Ok(Redirect::back())20}1use laravel::notification;2use laravel::prelude::*;34use crate::models::Invoice;5use crate::notifications::InvoicePaid;67pub async fn pay(Params(id): Params<i64>) -> laravel::Result<Redirect> {8 let invoice = Invoice::query()9 .with(Invoice::user)10 .find_or_fail(id)11 .await?;1213 // Charge the invoice...1415 notification::to(&invoice.user)16 .queue(InvoicePaid { invoice: invoice.clone() })17 .await?;1819 Ok(Redirect::back())20}
send delivers messages immediately and waits for each provider to accept them. to accepts a reference to a single notifiable, a slice or Vec of notifiables, a Vec of references, an Authenticated<User>, or a loaded relationship such as &invoice.user or &team.members. To notify multiple teams at once:
1let teams = Team::all().await?;23notification::to(&teams).send(WeeklySummary { report }).await?;1let teams = Team::all().await?;23notification::to(&teams).send(WeeklySummary { report }).await?;
When a single notification implements #[notification] for more than one notifiable type, Rust can't infer the target type from &Vec<T>, &Authenticated<T>, or a loaded relationship wrapper. In that case, pass a slice or dereference the wrapper instead:
1let teams = Team::all().await?;23notification::to(teams.as_slice()).send(InvoicePaid { invoice }).await?;1let teams = Team::all().await?;23notification::to(teams.as_slice()).send(InvoicePaid { invoice }).await?;
Queueing notifications
queue sends the messages from a queue worker, which retries each message when its provider fails, so start a worker before you queue notifications. Before you await queue, you may delay the messages and choose the queue their jobs go to:
1use laravel::time::ToSpan;23notification::to(&user)4 .queue(InvoicePaid { invoice })5 .delay(5.minutes())6 .on_queue("notifications")7 .await?;1use laravel::time::ToSpan;23notification::to(&user)4 .queue(InvoicePaid { invoice })5 .delay(5.minutes())6 .on_queue("notifications")7 .await?;
queue dispatches one job for each notifiable and channel, as queued mail and queued SMS do. Three users and two channels make six jobs, and a failed text message retries only that text message, never the email.
Without on_connection and on_queue, email jobs use MAIL_QUEUE_CONNECTION and MAIL_QUEUE, text message jobs use SMS_QUEUE_CONNECTION and SMS_QUEUE, and Slack and package channel jobs use the default connection and queue.
If you queue a notification inside a database transaction, Laravel waits to dispatch the jobs until the transaction commits. If the transaction rolls back, the queued notifications are discarded so users are never notified about changes that were not saved.
Choosing channels for each notifiable
By default, a notification is delivered on every channel defined in its #[notification] block. However, you may want to let individual users opt in or out of specific channels, or decide which channels to use based on the notification's data. To control delivery per recipient, add a channels method to your notification. For example, suppose your users table has an sms_alerts column configured on a settings page:
1use laravel::notification;2use laravel::notification::{Mail, Selected, Sms};34#[notification]5impl InvoicePaid {6 // `mail` and `sms` as before...78 fn channels(&self, user: &User, channels: &mut Selected<Self, User>) {9 channels.add(Mail);1011 if user.sms_alerts && self.invoice.total >= 10_000 {12 channels.add(Sms);13 }14 }15}1use laravel::notification;2use laravel::notification::{Mail, Selected, Sms};34#[notification]5impl InvoicePaid {6 // `mail` and `sms` as before...78 fn channels(&self, user: &User, channels: &mut Selected<Self, User>) {9 channels.add(Mail);1011 if user.sms_alerts && self.invoice.total >= 10_000 {12 channels.add(Sms);13 }14 }15}
channels runs once for each notifiable, before Laravel builds any message. It can't wait or fail, so it can't query the database. Load what it needs onto the notifiable or the notification before you send.
Package channels
Your users may want notifications where Laravel has no channel, such as Discord. A package can add that channel, and your notifications build its messages next to their email and text messages.
Sending through a package channel
To send through a package channel, annotate a method in your #[notification] impl with #[via(..)] and the channel type. For example, suppose a discord_notifications package provides a Discord channel sending a DiscordMessage to a webhook URL:
1use discord_notifications::{Discord, DiscordMessage};2use laravel::notification;3use laravel::notification::Receives;45#[notification]6impl InvoicePaid {7 // `mail` and `sms` as before...89 #[via(Discord)]10 fn discord(&self, _user: &User) -> DiscordMessage {11 DiscordMessage::new(format!("Invoice #{} is paid.", self.invoice.id))12 }13}1use discord_notifications::{Discord, DiscordMessage};2use laravel::notification;3use laravel::notification::Receives;45#[notification]6impl InvoicePaid {7 // `mail` and `sms` as before...89 #[via(Discord)]10 fn discord(&self, _user: &User) -> DiscordMessage {11 DiscordMessage::new(format!("Invoice #{} is paid.", self.invoice.id))12 }13}
The notifiable implements Receives<Discord>, whose route method returns the destination value defined by the package. Suppose your users table has a nullable discord_webhook_url column:
1impl Receives<Discord> for User {2 fn route(&self) -> Option<String> {3 self.discord_webhook_url.clone()4 }5}1impl Receives<Discord> for User {2 fn route(&self) -> Option<String> {3 self.discord_webhook_url.clone()4 }5}
As with built-in channels, a package channel is included by default whenever Receives<Discord>::route returns Some. If your notification defines a channels method to select channels per recipient, include the package channel by passing its channel type to channels.add:
1use discord_notifications::Discord;2use laravel::notification;3use laravel::notification::{Mail, Selected};45#[notification]6impl InvoicePaid {7 // `mail`, `sms`, and `discord` as before...89 fn channels(&self, user: &User, channels: &mut Selected<Self, User>) {10 channels.add(Mail);1112 if user.discord_alerts {13 channels.add(Discord);14 }15 }16}1use discord_notifications::Discord;2use laravel::notification;3use laravel::notification::{Mail, Selected};45#[notification]6impl InvoicePaid {7 // `mail`, `sms`, and `discord` as before...89 fn channels(&self, user: &User, channels: &mut Selected<Self, User>) {10 channels.add(Mail);1112 if user.discord_alerts {13 channels.add(Discord);14 }15 }16}
Passing a channel type to channels.add is type-checked: the code will only compile if the notification defines a #[via(Discord)] method and the notifiable implements Receives<Discord>.
Writing a channel
A channel is a unit struct with #[notification::channel] on its impl. The impl holds an async send function that takes a route and a message, and returns once the provider accepts the message. This is the Discord channel the package would provide:
1use laravel::http::client;2use laravel::notification;3use serde::{Deserialize, Serialize};45#[derive(Clone, Copy)]6pub struct Discord;78#[derive(Serialize, Deserialize)]9pub struct DiscordMessage {10 pub content: String,11}1213impl DiscordMessage {14 pub fn new(content: impl Into<String>) -> Self {15 Self { content: content.into() }16 }17}1819#[notification::channel(name = "discord")]20impl Discord {21 async fn send(webhook_url: String, message: DiscordMessage) -> laravel::Result<()> {22 client::post(webhook_url).json(&message).ensure_successful().await?;2324 Ok(())25 }2627 fn check(message: &DiscordMessage) -> laravel::Result<()> {28 if message.content.chars().count() > 2000 {29 return Err(laravel::abort_with(30 500,31 "a Discord message holds at most 2,000 characters",32 ));33 }3435 Ok(())36 }37}1use laravel::http::client;2use laravel::notification;3use serde::{Deserialize, Serialize};45#[derive(Clone, Copy)]6pub struct Discord;78#[derive(Serialize, Deserialize)]9pub struct DiscordMessage {10 pub content: String,11}1213impl DiscordMessage {14 pub fn new(content: impl Into<String>) -> Self {15 Self { content: content.into() }16 }17}1819#[notification::channel(name = "discord")]20impl Discord {21 async fn send(webhook_url: String, message: DiscordMessage) -> laravel::Result<()> {22 client::post(webhook_url).json(&message).ensure_successful().await?;2324 Ok(())25 }2627 fn check(message: &DiscordMessage) -> laravel::Result<()> {28 if message.content.chars().count() > 2000 {29 return Err(laravel::abort_with(30 500,31 "a Discord message holds at most 2,000 characters",32 ));33 }3435 Ok(())36 }37}
send's argument types become the channel's route and message types. Both must implement Serialize and Deserialize, because a queued job stores them. send runs in the application's context, so it may read configuration and resolve services, such as a config section that holds an API token.
The optional check function runs on each message as the notification builds it. A message the provider would refuse then fails in the code that sends it, and in your tests, rather than on the queue worker. Use it for limits the provider documents, such as Discord's 2,000 characters.
When you queue a notification for a custom channel, Laravel records the channel's name in the queued job payload so workers know which channel's send function to invoke. If you omit name, Laravel defaults to the struct's full Rust module path (such as discord_notifications::channels::Discord).
Giving your channel an explicit name decouples queued jobs from your module layout. That way, if you later move the struct to another module or rename it, jobs already sitting in the queue continue to run without failing:
1#[notification::channel(name = "discord")]2impl DiscordWebhook {3 async fn send(webhook_url: String, message: DiscordMessage) -> laravel::Result<()> {4 // ...5 }6}1#[notification::channel(name = "discord")]2impl DiscordWebhook {3 async fn send(webhook_url: String, message: DiscordMessage) -> laravel::Result<()> {4 // ...5 }6}
Testing
Most tests should check that your code sent a notification, not that a provider delivered it. notification::fake() records notifications instead of sending them. The fake still builds and renders each message as a real send would, so a template error or an invalid phone number fails the test:
1use laravel::model::create;2use laravel::notification;3use laravel::testing::prelude::*;45#[laravel::test]6async fn paying_an_invoice_notifies_the_customer(app: Application) -> laravel::Result<()> {7 let user = create!(User {8 name: "Taylor",10 password: "password",11 })12 .await?;1314 let invoice = create!(Invoice { user_id: user.id, total: 120_000 }).await?;1516 let notifications = notification::fake();1718 app.post(format!("/invoices/{}/pay", invoice.id)).await.assert_redirect();1920 notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {21 sent.notification().invoice.id == invoice.id && sent.sms().is_none()22 });2324 Ok(())25}1use laravel::model::create;2use laravel::notification;3use laravel::testing::prelude::*;45#[laravel::test]6async fn paying_an_invoice_notifies_the_customer(app: Application) -> laravel::Result<()> {7 let user = create!(User {8 name: "Taylor",10 password: "password",11 })12 .await?;1314 let invoice = create!(Invoice { user_id: user.id, total: 120_000 }).await?;1516 let notifications = notification::fake();1718 app.post(format!("/invoices/{}/pay", invoice.id)).await.assert_redirect();1920 notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {21 sent.notification().invoice.id == invoice.id && sent.sms().is_none()22 });2324 Ok(())25}
Every SentNotification passed to a predicate exposes the original notification via notification(), along with queued() to check whether it was queued rather than sent synchronously. You can also inspect the rendered email with mail() or the mailable struct that built it with mailable::<M>():
1notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {2 sent.queued()3 && sent4 .mail()5 .is_some_and(|email| email.subject() == format!("Invoice #{} is paid", invoice.id))6 && sent.mailable::<InvoicePaidEmail>().is_some_and(|mail| mail.name == user.name)7});1notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {2 sent.queued()3 && sent4 .mail()5 .is_some_and(|email| email.subject() == format!("Invoice #{} is paid", invoice.id))6 && sent.mailable::<InvoicePaidEmail>().is_some_and(|mail| mail.name == user.name)7});
Each channel accessor returns None when that channel was skipped for the notifiable (for example, Taylor above has no phone number, so sent.sms() is None). When an SMS was sent, use sms() to inspect the message:
1notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {2 sent.sms().is_some_and(|sms| sms.text().contains("Thanks!"))3});1notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {2 sent.sms().is_some_and(|sms| sms.text().contains("Thanks!"))3});
For Slack and custom package channels, pass the channel type to message::<C>() to inspect the built message:
1use discord_notifications::Discord;2use laravel::notification::Slack;34notifications.assert_sent_to_where::<InvoicePaid>(&team, |sent| {5 sent.message::<Slack>()6 .is_some_and(|message| message.text().contains(&format!("Invoice #{}", invoice.id)))7});89notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {10 sent.message::<Discord>()11 .is_some_and(|message| message.content.contains(&format!("Invoice #{}", invoice.id)))12});1use discord_notifications::Discord;2use laravel::notification::Slack;34notifications.assert_sent_to_where::<InvoicePaid>(&team, |sent| {5 sent.message::<Slack>()6 .is_some_and(|message| message.text().contains(&format!("Invoice #{}", invoice.id)))7});89notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {10 sent.message::<Discord>()11 .is_some_and(|message| message.content.contains(&format!("Invoice #{}", invoice.id)))12});
The fake has these assertions:
| Method | Asserts or returns |
|---|---|
assert_sent::<T>() |
A notification of type T was sent or queued at least once |
assert_sent_to::<T>(¬ifiable) |
A notification of type T was sent or queued to this notifiable |
assert_sent_to_where::<T>(¬ifiable, |
A notification of type T to this notifiable matches the predicate |
assert_not_sent_to::<T>(¬ifiable) |
No notification of type T was sent or queued to this notifiable |
assert_sent_where::<T>(predicate) |
A notification of type T, for one notifiable, matches the predicate |
assert_sent_times::<T>(count) |
Notifications of type T reached exactly count notifiables |
assert_not_sent::<T>() |
No notification of type T was sent or queued |
assert_nothing_sent() |
No notification was sent or queued |
sent::<T>() |
Each SentNotification of type T with its notification, in order |
The fake records both sent and queued notifications; use SentNotification::queued() to distinguish between them.
While the notification fake is active, notifications do not reach the mail fake or SMS fake. Without it, those fakes record notification messages alongside regular emails and text messages.