Skip to content

Notifications

Communication

Notifications

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 package channels such as Discord. Email uses mail and text messages use SMS. Both channels use 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

A notification is a type that holds the data its messages need. Its Messages method returns a notification.Messages, which holds the email in its Mail field and the messages for every other channel, such as a text message, in its Channels field. You may keep your notifications in a package such as app/notifications, one file for each.

For example, suppose your application has an Invoice model and an InvoicePaidEmail mailable. This notification alerts a user when their invoice is paid:

1// notifications/invoice_paid.go
2package notifications
3 
4import (
5 "fmt"
6 
7 "go.laravel.com/notification"
8 "go.laravel.com/sms"
9 
10 "app/mails"
11 "app/models"
12)
13 
14type InvoicePaid struct {
15 Invoice models.Invoice
16}
17 
18func (n InvoicePaid) Messages(user *models.User) (notification.Messages, error) {
19 return notification.Messages{
20 Mail: mails.InvoicePaidEmail{Name: user.Name, InvoiceID: n.Invoice.ID},
21 Channels: []any{
22 sms.Text{Body: fmt.Sprintf("Invoice #%d is paid. Thanks!", n.Invoice.ID)},
23 },
24 }, nil
25}
1// notifications/invoice_paid.go
2package notifications
3 
4import (
5 "fmt"
6 
7 "go.laravel.com/notification"
8 "go.laravel.com/sms"
9 
10 "app/mails"
11 "app/models"
12)
13 
14type InvoicePaid struct {
15 Invoice models.Invoice
16}
17 
18func (n InvoicePaid) Messages(user *models.User) (notification.Messages, error) {
19 return notification.Messages{
20 Mail: mails.InvoicePaidEmail{Name: user.Name, InvoiceID: n.Invoice.ID},
21 Channels: []any{
22 sms.Text{Body: fmt.Sprintf("Invoice #%d is paid. Thanks!", n.Invoice.ID)},
23 },
24 }, nil
25}

The method's argument is the notifiable that receives the messages, here a *models.User, and its type decides who the notification can go to. To send the same news to teams too, write a second notification type whose Messages method takes a *models.Team, as the Slack example does.

Laravel calls Messages once for each notifiable, in the handler or job that sends the notification, before it sends anything. Messages receives no ctx, so it can't query the database or build route URLs. Load the related models you need and build any URLs before you send the notification, and give the notification a field for each one. If Messages returns an error, the send stops before any message goes out.

Mail messages

Mail holds the email that one notifiable receives. It may be a mailable of your own or a mail.Message, which is a mailable too. InvoicePaidEmail is a mailable that renders resources/views/mails/invoice-paid.html with its Name and InvoiceID:

1// mails/invoice_paid.go
2package mails
3 
4import (
5 "fmt"
6 
7 "go.laravel.com/mail"
8)
9 
10type InvoicePaidEmail struct {
11 Name string
12 InvoiceID int64
13}
14 
15func (m InvoicePaidEmail) Build() mail.Message {
16 return mail.Message{
17 Subject: fmt.Sprintf("Invoice #%d is paid", m.InvoiceID),
18 View: "mails.invoice-paid",
19 Data: m,
20 }
21}
1// mails/invoice_paid.go
2package mails
3 
4import (
5 "fmt"
6 
7 "go.laravel.com/mail"
8)
9 
10type InvoicePaidEmail struct {
11 Name string
12 InvoiceID int64
13}
14 
15func (m InvoicePaidEmail) Build() mail.Message {
16 return mail.Message{
17 Subject: fmt.Sprintf("Invoice #%d is paid", m.InvoiceID),
18 View: "mails.invoice-paid",
19 Data: m,
20 }
21}

Laravel automatically addresses the email to the notifiable's mail address, so the mailable doesn't name a recipient. To learn more about views, subjects, and attachments, check out the mail guide.

SMS messages

A text message is an sms.Text in the notification's Channels. Laravel sends its Body from your SMS_FROM number. To send from another number, set the text's From:

1sms.Text{Body: fmt.Sprintf("Invoice #%d is paid.", n.Invoice.ID), From: "+15555550199"}
1sms.Text{Body: fmt.Sprintf("Invoice #%d is paid.", n.Invoice.ID), From: "+15555550199"}

Slack messages

A Slack message is a slack.Message in the notification's Channels, with blocks such as sections and buttons. Slack messages usually go to a team's channel rather than to one user, so they live in a notification whose Messages method takes a team. For example, suppose your application has a Team model with a slack_channel_id column. Because Messages can't build route URLs, the handler builds the invoice's URL with urls.Route(r, "invoices.show", "invoice", invoice.ID) and passes it in:

1// notifications/team_invoice_paid.go
2package notifications
3 
4import (
5 "go.laravel.com/notification"
6 "go.laravel.com/slack"
7 
8 "app/models"
9)
10 
11type TeamInvoicePaid struct {
12 Invoice models.Invoice
13 URL string
14}
15 
16func (n TeamInvoicePaid) Messages(team *models.Team) (notification.Messages, error) {
17 amount := slack.Markdownf("$%.2f", float64(n.Invoice.Total)/100)
18 
19 return notification.Messages{
20 Channels: []any{slack.Message{
21 Text: slack.Markdownf("Invoice #%d is paid", n.Invoice.ID),
22 Blocks: []slack.Block{
23 slack.Section{
24 Text: "Invoice paid.",
25 Fields: []slack.Field{{Label: "Amount", Value: amount}},
26 },
27 slack.Actions{Elements: []slack.Element{
28 slack.Button{Label: "View invoice", URL: n.URL},
29 }},
30 },
31 }},
32 }, nil
33}
1// notifications/team_invoice_paid.go
2package notifications
3 
4import (
5 "go.laravel.com/notification"
6 "go.laravel.com/slack"
7 
8 "app/models"
9)
10 
11type TeamInvoicePaid struct {
12 Invoice models.Invoice
13 URL string
14}
15 
16func (n TeamInvoicePaid) Messages(team *models.Team) (notification.Messages, error) {
17 amount := slack.Markdownf("$%.2f", float64(n.Invoice.Total)/100)
18 
19 return notification.Messages{
20 Channels: []any{slack.Message{
21 Text: slack.Markdownf("Invoice #%d is paid", n.Invoice.ID),
22 Blocks: []slack.Block{
23 slack.Section{
24 Text: "Invoice paid.",
25 Fields: []slack.Field{{Label: "Amount", Value: amount}},
26 },
27 slack.Actions{Elements: []slack.Element{
28 slack.Button{Label: "View invoice", URL: n.URL},
29 }},
30 },
31 }},
32 }, nil
33}

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 *models.User or *models.Team. For each channel it supports, a notifiable has a MailAddress, SMSNumber, or SlackRoute method that returns its email address, phone number, or Slack route. Suppose your users table also has a phone column, which holds a number in E.164 form or is empty, and your teams table has a slack_channel_id column:

1// models/user.go
2func (u User) MailAddress() mail.Address {
3 return mail.Address{Name: u.Name, Email: u.Email}
4}
5 
6func (u User) SMSNumber() string {
7 return u.Phone
8}
9 
10// models/team.go
11func (t Team) SlackRoute() slack.Route {
12 return slack.Route{Channel: t.SlackChannelID}
13}
1// models/user.go
2func (u User) MailAddress() mail.Address {
3 return mail.Address{Name: u.Name, Email: u.Email}
4}
5 
6func (u User) SMSNumber() string {
7 return u.Phone
8}
9 
10// models/team.go
11func (t Team) SlackRoute() slack.Route {
12 return slack.Route{Channel: t.SlackChannelID}
13}

When one of these methods returns its zero value, such as an empty phone number, 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 a method for every channel its notifications build. If User had no SMSNumber method, sending InvoicePaid, which builds a text message, would panic and name the interface to implement, here sms.Notifiable.

Sending notifications

To send a notification, pass the request, the notification, and its notifiables to notification.Queue or notification.Send. Most handlers should queue notifications so HTTP responses don't wait on external providers. This handler charges an invoice and notifies the customer:

1// handlers/invoices/pay.go
2package invoices
3 
4import (
5 "go.laravel.com/model"
6 "go.laravel.com/notification"
7 "go.laravel.com/web"
8 
9 "app/models"
10 "app/notifications"
11)
12 
13func Pay(r *web.Request) *web.Response {
14 invoice, err := model.FromRoute[models.Invoice](r, "invoice")
15 if err != nil {
16 return web.Fail(err)
17 }
18 customer, err := model.Find[models.User](r, invoice.UserID)
19 if err != nil {
20 return web.Fail(err)
21 }
22 
23 // Charge the invoice...
24 
25 if err := notification.Queue(r, notifications.InvoicePaid{Invoice: invoice}, &customer); err != nil {
26 return web.Fail(err)
27 }
28 
29 return web.Back()
30}
1// handlers/invoices/pay.go
2package invoices
3 
4import (
5 "go.laravel.com/model"
6 "go.laravel.com/notification"
7 "go.laravel.com/web"
8 
9 "app/models"
10 "app/notifications"
11)
12 
13func Pay(r *web.Request) *web.Response {
14 invoice, err := model.FromRoute[models.Invoice](r, "invoice")
15 if err != nil {
16 return web.Fail(err)
17 }
18 customer, err := model.Find[models.User](r, invoice.UserID)
19 if err != nil {
20 return web.Fail(err)
21 }
22 
23 // Charge the invoice...
24 
25 if err := notification.Queue(r, notifications.InvoicePaid{Invoice: invoice}, &customer); err != nil {
26 return web.Fail(err)
27 }
28 
29 return web.Back()
30}

Send delivers the messages immediately and waits for each provider to accept them. A command, a job, or a listener passes the ctx it received in place of r. Both functions take any number of notifiables, and when you have a slice of models from a query, such as []models.Team, pass it directly to notification.QueueAll or notification.SendAll:

1err := notification.SendAll(ctx, notifications.WeeklySummary{Report: report}, teams)
1err := notification.SendAll(ctx, notifications.WeeklySummary{Report: report}, teams)

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. You may delay the messages and choose the queue their jobs go to by starting with notification.Delay, notification.OnQueue, or notification.OnConnection, and chaining the others before Queue:

1err := notification.OnQueue("notifications").
2 Delay(5*time.Minute).
3 Queue(r, notifications.InvoicePaid{Invoice: invoice}, &customer)
1err := notification.OnQueue("notifications").
2 Delay(5*time.Minute).
3 Queue(r, notifications.InvoicePaid{Invoice: invoice}, &customer)

Queue builds and renders every message right away, so a template error queues nothing. Then it 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 OnConnection and OnQueue, 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, passing the transaction's ctx, 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. Send doesn't wait for the commit, so queue the notifications you send inside a transaction.

On-demand notifications

Sometimes you need to notify someone who isn't one of your models, such as your operations team's mailbox. notification.Routes is a notifiable that maps each channel's name to an address on that channel. For example, a command that imports data could tell operations when the import finishes:

1ops := notification.Routes{
2 "mail": mail.Addr("[email protected]", "Operations"),
3 "slack": slack.Route{Channel: "C0123ABCDEF"},
4}
5 
6err := notification.Send(ctx, notifications.ImportFinished{Rows: count}, ops)
1ops := notification.Routes{
2 "mail": mail.Addr("[email protected]", "Operations"),
3 "slack": slack.Route{Channel: "C0123ABCDEF"},
4}
5 
6err := notification.Send(ctx, notifications.ImportFinished{Rows: count}, ops)

Use a mail.Address for "mail", a phone number string for "sms", and a slack.Route for "slack". Laravel skips each channel that the routes don't name. A notification that you send on demand takes notification.Routes as its Messages argument:

1func (n ImportFinished) Messages(ops notification.Routes) (notification.Messages, error) {
2 return notification.Messages{
3 Mail: mail.Message{Subject: fmt.Sprintf("Imported %d rows", n.Rows)},
4 Channels: []any{slack.Message{Text: slack.Markdownf("Imported %d rows", n.Rows)}},
5 }, nil
6}
1func (n ImportFinished) Messages(ops notification.Routes) (notification.Messages, error) {
2 return notification.Messages{
3 Mail: mail.Message{Subject: fmt.Sprintf("Imported %d rows", n.Rows)},
4 Channels: []any{slack.Message{Text: slack.Markdownf("Imported %d rows", n.Rows)}},
5 }, nil
6}

Choosing channels for each notifiable

By default, a notifiable receives a message on every channel that Messages fills in for it. 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. Because Messages receives the notifiable, it can leave a channel's message out for that recipient. For example, suppose your users table has an sms_alerts column configured on a settings page:

1func (n InvoicePaid) Messages(user *models.User) (notification.Messages, error) {
2 messages := notification.Messages{
3 Mail: mails.InvoicePaidEmail{Name: user.Name, InvoiceID: n.Invoice.ID},
4 }
5 
6 if user.SMSAlerts && n.Invoice.Total >= 10_000 {
7 text := sms.Text{Body: fmt.Sprintf("Invoice #%d is paid.", n.Invoice.ID)}
8 messages.Channels = append(messages.Channels, text)
9 }
10 
11 return messages, nil
12}
1func (n InvoicePaid) Messages(user *models.User) (notification.Messages, error) {
2 messages := notification.Messages{
3 Mail: mails.InvoicePaidEmail{Name: user.Name, InvoiceID: n.Invoice.ID},
4 }
5 
6 if user.SMSAlerts && n.Invoice.Total >= 10_000 {
7 text := sms.Text{Body: fmt.Sprintf("Invoice #%d is paid.", n.Invoice.ID)}
8 messages.Channels = append(messages.Channels, text)
9 }
10 
11 return messages, nil
12}

In this example, every user gets the email, and only users who turned on text alerts get a text, and only for invoices of $100 or more.

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, add the channel's message to your notification's Channels. Laravel finds the channel by the message's type. For example, suppose a github.com/example/discord package provides a channel that sends a discord.Message to a webhook URL:

1func (n InvoicePaid) Messages(user *models.User) (notification.Messages, error) {
2 return notification.Messages{
3 Mail: mails.InvoicePaidEmail{Name: user.Name, InvoiceID: n.Invoice.ID},
4 Channels: []any{
5 discord.Message{Content: fmt.Sprintf("Invoice #%d is paid.", n.Invoice.ID)},
6 },
7 }, nil
8}
1func (n InvoicePaid) Messages(user *models.User) (notification.Messages, error) {
2 return notification.Messages{
3 Mail: mails.InvoicePaidEmail{Name: user.Name, InvoiceID: n.Invoice.ID},
4 Channels: []any{
5 discord.Message{Content: fmt.Sprintf("Invoice #%d is paid.", n.Invoice.ID)},
6 },
7 }, nil
8}

The notifiable implements the package's discord.Notifiable interface, whose DiscordWebhookURL method returns the webhook URL. Suppose your users table has a nullable discord_webhook_url column:

1// models/user.go
2func (u User) DiscordWebhookURL() string {
3 if u.DiscordWebhook == nil {
4 return ""
5 }
6 
7 return *u.DiscordWebhook
8}
1// models/user.go
2func (u User) DiscordWebhookURL() string {
3 if u.DiscordWebhook == nil {
4 return ""
5 }
6 
7 return *u.DiscordWebhook
8}

As with built-in channels, a user receives the Discord message whenever DiscordWebhookURL returns a URL. To let users choose their channels, leave the Discord message out of Channels for users who turned it off.

Writing a channel

A channel has a name, a method that its notifiables implement to give their route, and a function that sends one message to one route and returns once the provider accepts the message. notification.NewChannel builds a channel from these three parts. This is the Discord channel the package would provide, which posts each message with Laravel's HTTP client:

1// Package discord sends Laravel notifications to Discord webhooks.
2package discord
3 
4import (
5 "context"
6 "errors"
7 
8 "go.laravel.com/httpclient"
9 "go.laravel.com/notification"
10)
11 
12// Notifiable receives Discord notifications at a webhook URL.
13type Notifiable interface {
14 DiscordWebhookURL() string
15}
16 
17// Message is a Discord message.
18type Message struct {
19 Content string `json:"content"`
20}
21 
22// Validate checks the message against Discord's limits.
23func (m Message) Validate() error {
24 if len([]rune(m.Content)) > 2000 {
25 return errors.New("a Discord message holds at most 2,000 characters")
26 }
27 
28 return nil
29}
30 
31// Channel sends Discord messages to each notifiable's webhook URL.
32var Channel = notification.NewChannel("discord", Notifiable.DiscordWebhookURL, send)
33 
34func send(ctx context.Context, webhookURL string, message Message) error {
35 _, err := httpclient.JSON(message).EnsureSuccessful().Post(ctx, webhookURL)
36 
37 return err
38}
1// Package discord sends Laravel notifications to Discord webhooks.
2package discord
3 
4import (
5 "context"
6 "errors"
7 
8 "go.laravel.com/httpclient"
9 "go.laravel.com/notification"
10)
11 
12// Notifiable receives Discord notifications at a webhook URL.
13type Notifiable interface {
14 DiscordWebhookURL() string
15}
16 
17// Message is a Discord message.
18type Message struct {
19 Content string `json:"content"`
20}
21 
22// Validate checks the message against Discord's limits.
23func (m Message) Validate() error {
24 if len([]rune(m.Content)) > 2000 {
25 return errors.New("a Discord message holds at most 2,000 characters")
26 }
27 
28 return nil
29}
30 
31// Channel sends Discord messages to each notifiable's webhook URL.
32var Channel = notification.NewChannel("discord", Notifiable.DiscordWebhookURL, send)
33 
34func send(ctx context.Context, webhookURL string, message Message) error {
35 _, err := httpclient.JSON(message).EnsureSuccessful().Post(ctx, webhookURL)
36 
37 return err
38}

The send function's argument types become the channel's route and message types. A queued job stores both as JSON, so they must encode to JSON and decode back, as a string and a struct with json tags do. The send function receives the worker's or the sender's ctx, so it may read configuration and the application's services, such as an API token.

When the message type has a Validate() error method, as Message does, Laravel calls it 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 the send function fails, the queued job tries again, unless the error has a Permanent() bool method that returns true. The error that EnsureSuccessful returns for a deleted webhook's 404 already has that method, so the Discord channel above stops retrying with no code of its own.

When you queue a notification for a package channel, Laravel records the channel's name, here "discord", in the queued job so workers know which channel's send function to call. Keep the name the same once your package is in use, so jobs already sitting in the queue continue to run.

The package registers its channel in its Register method, and every application that installs the package may then send through it:

1func (p *Package) Register(app *laravel.Registrar) error {
2 app.NotificationChannels(Channel)
3 
4 return nil
5}
1func (p *Package) Register(app *laravel.Registrar) error {
2 app.NotificationChannels(Channel)
3 
4 return nil
5}

If you write a channel inside your own application instead, list it in your application's options in bootstrap/app.go, as in NotificationChannels: []notification.Channel{discord.Channel}. The application fails to start when two channels share a name or a message type.

Testing

Most tests should check that your code sent a notification, not that a provider delivered it. A notificationtest.Fake records notifications instead of sending them. Build the client, then pass it to notificationtest.New, which installs the fake in the client's application. The fake still builds, renders, and validates each message as a real send would, so a template error or a Discord message that's too long fails the test:

1package feature_test
2 
3import (
4 "fmt"
5 "testing"
6 
7 "go.laravel.com/model"
8 "go.laravel.com/notificationtest"
9 
10 "app/models"
11 "app/notifications"
12 "app/tests"
13)
14 
15func TestPayingAnInvoiceNotifiesTheCustomer(t *testing.T) {
16 client := tests.New(t)
17 sent := notificationtest.New(client)
18 
19 customer := models.User{Name: "Taylor", Email: "[email protected]"}
20 if err := model.Create(client.Context(), &customer); err != nil {
21 t.Fatal(err)
22 }
23 
24 invoice := models.Invoice{UserID: customer.ID, Total: 120_000}
25 if err := model.Create(client.Context(), &invoice); err != nil {
26 t.Fatal(err)
27 }
28 
29 client.Post(fmt.Sprintf("/invoices/%d/pay", invoice.ID), nil).AssertRedirectBack()
30 
31 sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
32 return paid.Notification.Invoice.ID == invoice.ID && paid.Mail != nil
33 })
34}
1package feature_test
2 
3import (
4 "fmt"
5 "testing"
6 
7 "go.laravel.com/model"
8 "go.laravel.com/notificationtest"
9 
10 "app/models"
11 "app/notifications"
12 "app/tests"
13)
14 
15func TestPayingAnInvoiceNotifiesTheCustomer(t *testing.T) {
16 client := tests.New(t)
17 sent := notificationtest.New(client)
18 
19 customer := models.User{Name: "Taylor", Email: "[email protected]"}
20 if err := model.Create(client.Context(), &customer); err != nil {
21 t.Fatal(err)
22 }
23 
24 invoice := models.Invoice{UserID: customer.ID, Total: 120_000}
25 if err := model.Create(client.Context(), &invoice); err != nil {
26 t.Fatal(err)
27 }
28 
29 client.Post(fmt.Sprintf("/invoices/%d/pay", invoice.ID), nil).AssertRedirectBack()
30 
31 sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
32 return paid.Notification.Invoice.ID == invoice.ID && paid.Mail != nil
33 })
34}

The fake records one notificationtest.Sent for each notifiable. Its Notification field is the original notification, and its Queued field tells you whether it was queued rather than sent. You can also inspect the rendered email in its Mail field, and extract the mailable that built the email with Mailable:

1sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
2 if !paid.Queued || paid.Mail == nil {
3 return false
4 }
5 email, ok := paid.Mailable[mails.InvoicePaidEmail]()
6 
7 return ok &&
8 paid.Mail.Subject == fmt.Sprintf("Invoice #%d is paid", invoice.ID) &&
9 email.Name == customer.Name
10})
1sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
2 if !paid.Queued || paid.Mail == nil {
3 return false
4 }
5 email, ok := paid.Mailable[mails.InvoicePaidEmail]()
6 
7 return ok &&
8 paid.Mail.Subject == fmt.Sprintf("Invoice #%d is paid", invoice.ID) &&
9 email.Name == customer.Name
10})

Mail is nil when the notifiable received no email. For every other channel, Message returns the message the notifiable received, and false when the channel was skipped. For example, Taylor above has no phone number, so no text message was sent. For a customer with one, check the text:

1sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
2 text, ok := paid.Message[sms.Text]()
3 
4 return ok && strings.Contains(text.Body, "Thanks!")
5})
1sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
2 text, ok := paid.Message[sms.Text]()
3 
4 return ok && strings.Contains(text.Body, "Thanks!")
5})

To inspect a Slack or package channel message, call Message with that message's type as well:

1sent.AssertSentTo(&team, func(paid notificationtest.Sent[notifications.TeamInvoicePaid]) bool {
2 message, ok := paid.Message[slack.Message]()
3 
4 return ok && strings.Contains(string(message.Text), fmt.Sprintf("Invoice #%d", invoice.ID))
5})
6 
7sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
8 message, ok := paid.Message[discord.Message]()
9 
10 return ok && strings.Contains(message.Content, fmt.Sprintf("Invoice #%d", invoice.ID))
11})
1sent.AssertSentTo(&team, func(paid notificationtest.Sent[notifications.TeamInvoicePaid]) bool {
2 message, ok := paid.Message[slack.Message]()
3 
4 return ok && strings.Contains(string(message.Text), fmt.Sprintf("Invoice #%d", invoice.ID))
5})
6 
7sent.AssertSentTo(&customer, func(paid notificationtest.Sent[notifications.InvoicePaid]) bool {
8 message, ok := paid.Message[discord.Message]()
9 
10 return ok && strings.Contains(message.Content, fmt.Sprintf("Invoice #%d", invoice.ID))
11})

The fake's assertions take the notification's type. AssertSent and AssertSentTo also take optional functions that receive each notificationtest.Sent, and when you pass one, Go infers the type from it, as the examples above do. Without one, name the type, as in sent.AssertSentTo[notifications.InvoicePaid](&customer). The fake has these assertions:

Method Asserts or returns
AssertSent[T](match...) A notification of type T was sent or queued at least once, and matches when you pass match
AssertSentTo[T](notifiable, match...) A notification of type T was sent or queued to this notifiable, and matches when you pass match
AssertNotSentTo[T](notifiable) No notification of type T was sent or queued to this notifiable
AssertSentTimes[T](count) Notifications of type T reached exactly count notifiables
AssertNotSent[T]() No notification of type T was sent or queued
AssertNothingSent() No notification was sent or queued
Sent[T]() Each notificationtest.Sent of type T with its notification, in order

The fake tells notifiables apart by their address and routes, so the test's own customer matches the user that the handler loaded. It records a queued notification in place of queueing it, so the test needs no worker, and a notification queued inside a transaction is recorded when the transaction commits. Use the Queued field to tell sent and queued notifications apart.

While the notification fake is active, notifications don't reach the mail fake or SMS fake. Without it, those fakes record notification messages alongside your other email and text messages.