Events
- Introduction
- Defining events
- Defining listeners
- Dispatching events
- Queued listeners
- Database transactions
- Testing events
Introduction
Events let you decouple the parts of your application, so a single action can trigger several side effects. When a customer places an order, you may want to email a receipt, record an audit log entry, and notify the warehouse. Rather than growing your order code with every new step, dispatch an OrderPlaced event and let independent listeners react to it.
An event is a plain Go struct, and a listener is a function that takes a context and an event. You list your listeners in listeners.All, and your code dispatches events with event.Dispatch. Models also dispatch model events when you create, update, or delete them, and broadcasting lets you push events to the browser over WebSockets.
Defining events
An event is a struct that holds what its listeners need to know. You may keep your events in an events package:
// events/order_placed.go
package events
type OrderPlaced struct {
OrderID int64
Email string
Total int64
}An event needs no methods or tags. Copy the IDs and values your listeners need into the event, rather than the *web.Request, so the listeners also work when a command or a test dispatches the event.
Defining listeners
A listener is a function that takes a context.Context and an event, and returns an error. New applications keep listeners in the listeners package. For example, this listener emails an OrderReceipt mailable to the customer:
// listeners/send_receipt.go
package listeners
import (
"context"
"go.laravel.com/mail"
"app/events"
"app/mails"
)
func SendReceipt(ctx context.Context, e events.OrderPlaced) error {
receipt := mails.OrderReceipt{OrderID: e.OrderID}
return mail.To(mail.Addr(e.Email)).Send(ctx, receipt)
}The listener reaches the rest of your application through its ctx, as a handler does through r. Queries and model writes with ctx run on your database, config.From(ctx) returns your configuration, and services.From(ctx) returns your own services, such as a payment provider's client. The listener receives the context that the event was dispatched with, so during a request, auth.User returns the logged-in user.
Registering listeners
A listener runs only once you register it. New applications list their listeners in listeners.All, which bootstrap.Options passes to the application. Wrap each function in laravel.Listen, which takes the event's type from the function's second argument:
// listeners/listeners.go
package listeners
import laravel "go.laravel.com"
var All = []laravel.Listener{
laravel.Listen(SendReceipt),
laravel.Listen(RecordAuditEntry),
}An event may have any number of listeners. They run one after another, in the order you list them.
Listening for several events
Sometimes one listener should react to several kinds of events, such as recording an audit entry for every change a user makes. When a listener's event type is an interface, the listener receives every event that implements the interface. For example, if each of your auditable events has an AuditEntry method, one listener can record all of them:
// listeners/record_audit_entry.go
package listeners
import (
"context"
"go.laravel.com/db"
)
type Auditable interface {
AuditEntry() string
}
func RecordAuditEntry(ctx context.Context, e Auditable) error {
return db.Table("audit_entries").Insert(ctx, db.Values{"entry": e.AuditEntry()})
}A listener of any receives every event your application dispatches.
Listeners from packages
A package may react to your application's events too, such as sending a quote to each new user. A package registers its listeners in its Register method with app.Listeners:
func (q *Quotes) Register(app *laravel.Registrar) error {
app.Listeners(laravel.Listen(q.QuoteOnSignUp))
return nil
}A package's listeners run before the application's own listeners of the same event.
Dispatching events
To notify an event's listeners, pass the event to event.Dispatch with a context. For example, given an Order model, this function creates an order and dispatches OrderPlaced:
// store/orders.go
package store
import (
"context"
"go.laravel.com/event"
"go.laravel.com/model"
"app/events"
"app/models"
)
func PlaceOrder(ctx context.Context, customer models.User, total int64) (models.Order, error) {
order := models.Order{UserID: customer.ID, Total: total}
if err := model.Create(ctx, &order); err != nil {
return models.Order{}, err
}
err := event.Dispatch(ctx, events.OrderPlaced{
OrderID: order.ID,
Email: customer.Email,
Total: total,
})
return order, err
}Dispatch runs the event's listeners one after another and returns once they've all finished. A handler calls PlaceOrder with r, which is a context.Context, and a command or a job passes the ctx it received.
Failures
If a listener returns an error, the event's remaining listeners don't run, and Dispatch returns that error. A handler that passes the error to web.Fail responds with an error response. The order is already saved, so to keep a failing listener from failing the request, report the error with laravel.Report instead of returning it:
err := event.Dispatch(ctx, events.OrderPlaced{
OrderID: order.ID,
Email: customer.Email,
Total: total,
})
if err != nil {
laravel.Report(ctx, err)
}
return order, nilInside a database transaction, listeners run after the transaction commits, so db.Transaction reports their errors instead.
Dispatching in the background
When the caller doesn't need to wait for the listeners, such as a listener that pings an analytics service, dispatch the event as background work. laravel.Background runs the dispatch in a goroutine of its own and returns at once:
placed := events.OrderPlaced{OrderID: order.ID, Email: customer.Email, Total: total}
laravel.Background(ctx, func(ctx context.Context) error {
return event.Dispatch(ctx, placed)
})In a handler, call r.Background with the same function. Because nobody waits for the listeners, Laravel reports their errors. Inside a database transaction, the background work starts only after the transaction commits, and a rollback discards it. When the server shuts down, it waits for background work up to SERVER_SHUTDOWN_TIMEOUT.
警告
Background work is kept only in memory and isn't retried, so a crash or restart can lose it. For work that must complete reliably, use a queued listener.
Queued listeners
When a listener performs slow work, such as sending an email or calling another service, run it on your queue instead. The queue stores the work until a worker runs it, so a queued listener has two parts: a job, whose fields hold what the work needs and whose Handle method does the work, and a function that builds the job from the event. For example, this queued listener replaces the SendReceipt function from Defining listeners:
// listeners/send_receipt.go
package listeners
import (
"context"
"go.laravel.com/mail"
"app/events"
"app/mails"
)
type SendReceipt struct {
OrderID int64
Email string
}
func QueueReceipt(e events.OrderPlaced) SendReceipt {
return SendReceipt{OrderID: e.OrderID, Email: e.Email}
}
func (j SendReceipt) Handle(ctx context.Context) error {
receipt := mails.OrderReceipt{OrderID: j.OrderID}
return mail.To(mail.Addr(j.Email)).Send(ctx, receipt)
}Register the listener with laravel.ListenQueued, which takes the event's type from the function's argument:
var All = []laravel.Listener{
laravel.ListenQueued(QueueReceipt),
}Dispatching OrderPlaced now pushes a SendReceipt job, so a queue worker runs the listener's work, while the event's other listeners still run in the dispatch. Laravel adds the job type of each queued listener to your queue's jobs, so you don't list it in jobs.All. Inside a database transaction, the job is pushed only after the transaction commits, like any queued job.
The job is an ordinary job, so its Handle may release, delete, or fail its run. The queue stores the job's fields as JSON, so copy the IDs and values the work needs out of the event, as QueueReceipt does. A job field may also hold a model, which the worker reads from the database again before Handle runs. If the model's row has been deleted by then, the worker deletes the job without running it, unless the job's options set FailWhenMissingModels.
Queue options
A receipt email might belong on an emails queue and get a few retries in case your mail provider is down. Give the job a JobOptions method to choose its queue, tries, backoff, and timeout, as for any job:
func (SendReceipt) JobOptions() queue.Options {
return queue.Options{
Queue: "emails",
Tries: 3,
Backoff: []time.Duration{time.Minute},
}
}To push the job to another connection, or to delay it, call Connection and Delay on the listener when you register it in listeners.All:
laravel.ListenQueued(QueueReceipt).Connection("redis").Delay(10 * time.Minute)The queue stores the job under its type's name, such as app/listeners.SendReceipt. Before you rename or move a queued listener whose jobs may still be waiting, give the job a JobName method that returns the old name.
Job methods
When a queued listener needs more than Handle, give its job any of the optional methods below Handle in this table:
| Method | Purpose |
|---|---|
Handle(ctx) error | Runs the listener's work on the worker. |
Failed(ctx, err) error | Cleans up when the job fails for good. |
ShouldQueue() bool | Returns false to skip pushing the job for this event. |
JobOptions() queue.Options | Chooses the job's queue, tries, backoff, timeout, and debouncing. |
Middleware() []queue.Middleware | Returns job middleware that wraps Handle. |
DebounceID() string | Groups debounced runs. |
For example, this listener awards a gift card for orders of $50 or more (Total is in cents), and logs a warning if every try fails:
// listeners/reward_gift_card.go
package listeners
import (
"context"
"log/slog"
"go.laravel.com/model"
"go.laravel.com/queue"
"app/events"
"app/models"
)
type RewardGiftCard struct {
OrderID int64
Total int64
}
func QueueGiftCard(e events.OrderPlaced) RewardGiftCard {
return RewardGiftCard{OrderID: e.OrderID, Total: e.Total}
}
func (j RewardGiftCard) ShouldQueue() bool {
return j.Total >= 5000
}
func (RewardGiftCard) JobOptions() queue.Options {
return queue.Options{Queue: "rewards", Tries: 3}
}
func (j RewardGiftCard) Handle(ctx context.Context) error {
return model.Create(ctx, &models.GiftCard{OrderID: j.OrderID, Amount: 500})
}
func (j RewardGiftCard) Failed(ctx context.Context, err error) error {
slog.WarnContext(ctx, "Couldn't reward a gift card.", "order", j.OrderID, "error", err)
return nil
}ShouldQueue runs before the job is pushed, so a skipped event never reaches the queue.
Debouncing listeners
When an event fires repeatedly in quick succession, you may want to handle only the final occurrence. For example, a user who saves their profile five times in a minute should receive one confirmation email, not five. Listen for the model.Updated[models.User] event, and give the job a DebounceFor option and a DebounceID method that groups related events:
// listeners/send_profile_updated_email.go
package listeners
import (
"context"
"strconv"
"time"
"go.laravel.com/mail"
"go.laravel.com/model"
"go.laravel.com/queue"
"app/mails"
"app/models"
)
type SendProfileUpdatedEmail struct {
User models.User `queue:"model"`
}
func QueueProfileUpdatedEmail(e model.Updated[models.User]) SendProfileUpdatedEmail {
return SendProfileUpdatedEmail{User: e.Model}
}
func (SendProfileUpdatedEmail) JobOptions() queue.Options {
return queue.Options{DebounceFor: time.Minute}
}
func (j SendProfileUpdatedEmail) DebounceID() string {
return strconv.FormatInt(j.User.ID, 10)
}
func (j SendProfileUpdatedEmail) Handle(ctx context.Context) error {
return mail.To(j.User).Send(ctx, mails.ProfileUpdated{User: j.User})
}Each user now receives a single email one minute after their last update. Without DebounceID, every SendProfileUpdatedEmail job would replace the ones before it, across all users. To make sure the email still goes out when a user keeps saving, cap the wait with MaxWait, such as queue.Options{DebounceFor: time.Minute, MaxWait: 5 * time.Minute}.
The queue tracks debounced jobs in your default cache store, so use a store that every server shares, such as database or redis. To learn more about debouncing options, check out the queues guide's section on debounced jobs.
Database transactions
Events dispatched inside a database transaction wait until the outermost transaction commits before running their listeners. If the transaction rolls back, Laravel discards the pending events, so listeners never send receipts or read rows that were never saved. Outside a transaction, Dispatch runs listeners immediately. Jobs and broadcasts also wait for transactions to commit.
For example, this version of PlaceOrder saves an order and its payment together, and dispatches OrderPlaced only once both commit:
// store/orders.go
package store
import (
"context"
"go.laravel.com/db"
"go.laravel.com/event"
"go.laravel.com/model"
"app/events"
"app/models"
)
func PlaceOrder(ctx context.Context, customer models.User, total int64) (models.Order, error) {
order := models.Order{UserID: customer.ID, Total: total}
err := db.Transaction(ctx, func(ctx context.Context) error {
if err := model.Create(ctx, &order); err != nil {
return err
}
payment := models.Payment{OrderID: order.ID, Amount: total}
if err := model.Create(ctx, &payment); err != nil {
return err
}
return event.Dispatch(ctx, events.OrderPlaced{
OrderID: order.ID,
Email: customer.Email,
Total: total,
})
})
return order, err
}Inside the transaction, Dispatch returns nil immediately and holds the event until the commit. If a held listener fails after the commit, the order is already saved, so db.Transaction reports the listener's error and returns nil. To learn more about work that waits for a commit, check out the database guide's section on after-commit work.
Dispatch with the ctx that db.Transaction passes to its function. A context from outside the function, such as a handler's r, isn't in the transaction, so its dispatch runs the listeners at once, before the commit.
Running listeners in the transaction
Some listeners must take part in the transaction itself, such as one that reserves stock, which should succeed or roll back alongside the order. Register those listeners with laravel.ListenAtDispatch, so they run immediately when you dispatch the event instead of waiting for the commit:
// listeners/reserve_stock.go
package listeners
import (
"context"
"go.laravel.com/model"
"app/events"
"app/models"
)
func ReserveStock(ctx context.Context, e events.OrderPlaced) error {
return model.Create(ctx, &models.Reservation{OrderID: e.OrderID})
}var All = []laravel.Listener{
laravel.ListenAtDispatch(ReserveStock),
laravel.ListenQueued(QueueReceipt),
}The listener receives the dispatch's ctx, which is in the transaction, so its writes commit or roll back with the order. Its error fails Dispatch, and returning that error from the transaction's function rolls the transaction back. The event's other listeners still wait for the commit. Keep these listeners fast, because the transaction holds its row locks while they run.
Some events belong inside the transaction as a whole, such as a StockReserved event whose every listener writes rows that must roll back with the order. To run every listener of an event at dispatch time, including those registered with laravel.Listen, give the event an AtDispatch method that returns true:
type StockReserved struct {
OrderID int64
}
func (StockReserved) AtDispatch() bool {
return true
}Testing events
When you test code that dispatches events, you usually want to check that it dispatched the right event, and test the listeners on their own. eventtest.New installs a fake in your test's application that records dispatched events instead of running their listeners. Pass it the test client, then make assertions on the fake it returns:
// tests/feature/orders_test.go
package feature_test
import (
"testing"
"go.laravel.com/eventtest"
"app/database/factories"
"app/events"
"app/tests"
)
func TestPlacingAnOrderDispatchesAnEvent(t *testing.T) {
client := tests.New(t)
user := client.Create(factories.User)
dispatched := eventtest.New(client)
client.ActingAs(&user).
PostJSON("/api/orders", map[string]any{"total": 2500}).
AssertCreated()
dispatched.AssertDispatched[events.OrderPlaced]()
dispatched.AssertDispatched(func(e events.OrderPlaced) bool {
return e.Email == user.Email && e.Total == 2500
})
dispatched.AssertDispatchedTimes[events.OrderPlaced](1)
}You may also call AssertNotDispatched, which takes a type or a match function, and AssertNothingDispatched(). To inspect the recorded events directly, dispatched.Dispatched[events.OrderPlaced]() returns them in the order they were dispatched.
The fake records model events too, such as the model.Created[models.User] event of a user that a factory creates. Create the rows your test needs before you install the fake, as the test above does, so the fake records only what the request dispatched. Each test builds its own application with tests.New, so tests that run in parallel never see each other's events.
Faking selected events
To fake only specific events while all other events run their listeners as usual, name them with eventtest.Only:
dispatched := eventtest.New(client,
eventtest.Only(events.OrderPlaced{}, events.OrderCancelled{}),
)To fake every event except specific ones, use eventtest.Except, such as eventtest.New(client, eventtest.Except(events.OrderShipped{})).
Testing a listener
To test a single listener without running the other listeners of the same event, call the listener with client.Context() and an event. The context carries the application under test, so the listener's queries run on the test's database, and fakes you install on the client, such as the mail fake, apply to the listener too:
func TestReservingStock(t *testing.T) {
client := tests.New(t)
if err := listeners.ReserveStock(client.Context(), events.OrderPlaced{OrderID: 42}); err != nil {
t.Fatal(err)
}
client.AssertDatabaseHas("reservations", db.Values{"order_id": 42})
}With RefreshDatabase, listeners that wait for a commit still run once your application's own transaction commits, even though the test rolls everything back afterwards.
Testing queued listeners
A queued listener pushes a job. To verify that dispatching an event queued the listener's job, use the queue fake:
func TestPlacingAnOrderQueuesTheReceipt(t *testing.T) {
client := tests.New(t)
user := client.Create(factories.User)
queued := queuetest.New(client)
client.ActingAs(&user).
PostJSON("/api/orders", map[string]any{"total": 2500}).
AssertCreated()
queued.AssertPushed(func(job queuetest.Job[listeners.SendReceipt]) bool {
return job.Job.Email == user.Email && job.Queue == "emails"
})
}Because the event fake keeps listeners from running at all, nothing reaches the queue when both fakes are installed. Use the queue fake on its own when you test queued listeners.
To test the job's work, such as a release or a failure, build the job with your function and run one attempt with client.Attempt:
job := listeners.QueueReceipt(events.OrderPlaced{
OrderID: 42,
Email: "taylor@example.com",
Total: 2500,
})
client.Attempt(job).AssertSucceeded()