Events
- Introduction
- Defining events
- Defining listeners
- Dispatching events
- Queued listeners
- Database transactions
- Testing events
Introduction
Events provide a clean way to decouple parts of your application so a single action can trigger multiple 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 logic with every new step, dispatch an OrderPlaced event and let independent listeners react to it.
An event is a plain Rust struct, and a listener is an async function marked with #[listener]. Laravel discovers your listeners automatically when the application boots, so no manual registration is required. Models also dispatch model events when created, updated, or deleted, and broadcasting lets you push events to the browser over WebSockets.
Defining events
An event is a struct that derives Event. New applications keep events in src/events/:
1use laravel::event::Event;23#[derive(Event)]4pub struct OrderPlaced {5 pub order_id: i64,6 pub email: String,7 pub total: i64,8}1use laravel::event::Event;23#[derive(Event)]4pub struct OrderPlaced {5 pub order_id: i64,6 pub email: String,7 pub total: i64,8}
Events store owned values (such as String rather than &str), so clone or copy any data your listeners need instead of borrowing from the request.
Defining listeners
A listener is an async function annotated with #[listener]. Its first parameter is Event<T>, which dereferences to your event struct, and it returns either () or laravel::Result<()>. New applications keep listeners in src/listeners/. For example, this listener emails an OrderReceipt mailable:
1use laravel::event::{Event, listener};2use laravel::mail;34use crate::events::OrderPlaced;5use crate::mail::OrderReceipt;67#[listener]8pub async fn send_receipt(event: Event<OrderPlaced>) -> laravel::Result<()> {9 mail::to(&event.email)10 .send(OrderReceipt {11 order_id: event.order_id,12 })13 .await?;1415 Ok(())16}1use laravel::event::{Event, listener};2use laravel::mail;34use crate::events::OrderPlaced;5use crate::mail::OrderReceipt;67#[listener]8pub async fn send_receipt(event: Event<OrderPlaced>) -> laravel::Result<()> {9 mail::to(&event.email)10 .send(OrderReceipt {11 order_id: event.order_id,12 })13 .await?;1415 Ok(())16}
Like HTTP handlers, listeners may accept services via Inject<T> and config sections via Section<T> in any order after the event parameter.
Discovering tagged listeners
Laravel automatically discovers #[listener] functions in your application's app library crate. You may place them in any module as long as src/lib.rs declares the module so it is compiled. New applications declare pub mod listeners and mark listeners pub so tests can reference them directly.
Packages opt into listener discovery inside their service provider's register method:
1use laravel::container::Registrar;23fn register(&self, app: &mut Registrar) {4 app.events().discover(env!("CARGO_CRATE_NAME"));5}1use laravel::container::Registrar;23fn register(&self, app: &mut Registrar) {4 app.events().discover(env!("CARGO_CRATE_NAME"));5}
If your application's library crate is not named app, call events.discover(env!("CARGO_CRATE_NAME")) inside with_events in src/app.rs.
Registering listeners
To register a listener without #[listener] (such as an inline closure or a function defined in another crate), call events.listen inside with_events in src/app.rs. Laravel infers the event type from the listener's first argument:
1use laravel::event::Event;23Application::configure()4 .with_events(|events, _config| {5 events.listen(async |event: Event<OrderPlaced>| {6 tracing::info!(order_id = event.order_id, "Order placed");7 });8 })1use laravel::event::Event;23Application::configure()4 .with_events(|events, _config| {5 events.listen(async |event: Event<OrderPlaced>| {6 tracing::info!(order_id = event.order_id, "Order placed");7 });8 })
Packages can register listeners manually in their service provider's register method using app.events().listen(..).
Do not also pass a #[listener] function to events.listen, or it will run twice for every dispatch.
Dispatching events
Call dispatch on an event instance to notify its listeners. For example, given an Order model, this function creates an order and dispatches OrderPlaced:
1use laravel::model::create;23use crate::events::OrderPlaced;4use crate::models::{Order, User};56pub async fn place_order(user: &User, total: i64) -> laravel::Result<Order> {7 let order = create!(Order {8 user_id: user.id,9 total,10 })11 .await?;1213 OrderPlaced {14 order_id: order.id,15 email: user.email.clone(),16 total,17 }18 .dispatch()19 .await?;2021 Ok(order)22}1use laravel::model::create;23use crate::events::OrderPlaced;4use crate::models::{Order, User};56pub async fn place_order(user: &User, total: i64) -> laravel::Result<Order> {7 let order = create!(Order {8 user_id: user.id,9 total,10 })11 .await?;1213 OrderPlaced {14 order_id: order.id,15 email: user.email.clone(),16 total,17 }18 .dispatch()19 .await?;2021 Ok(order)22}
dispatch invokes the event's listeners sequentially and resolves once all of them finish.
Failures
If a listener returns an error, any remaining listeners are skipped and dispatch returns that error. A handler propagating the error with ? returns an error response. To prevent a failing listener from failing the request, report the error instead of returning it:
1let event = OrderPlaced {2 order_id: order.id,3 email: user.email.clone(),4 total,5};67if let Err(error) = event.dispatch().await {8 laravel::report(error);9}1let event = OrderPlaced {2 order_id: order.id,3 email: user.email.clone(),4 total,5};67if let Err(error) = event.dispatch().await {8 laravel::report(error);9}
Inside a database transaction, listeners run after the transaction commits, so listener errors are returned by db::transaction instead.
Background dispatch
When a request does not need to wait for listeners to complete, call dispatch_background. It launches the listeners in a background task within the current process and returns immediately without .await:
1OrderPlaced {2 order_id: order.id,3 email: user.email.clone(),4 total,5}6.dispatch_background()?;1OrderPlaced {2 order_id: order.id,3 email: user.email.clone(),4 total,5}6.dispatch_background()?;
Because no caller awaits the task, Laravel reports any listener errors automatically. Inside a database transaction, the background task starts only after the transaction commits, and a rollback discards it. During graceful shutdown, the server waits for in-flight background events up to SERVER_SHUTDOWN_TIMEOUT.
Background events are kept only in memory and are not retried, so a crash or restart can lose them. 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 a third-party API, run it on your queue with #[listener(queued)]. Because the queue serializes the event until a worker processes it, the event must also derive Queueable:
1use laravel::event::{Event, listener};2use laravel::mail;3use laravel::queue::Queueable;45use crate::mail::OrderReceipt;67#[derive(Event, Queueable)]8pub struct OrderPlaced {9 pub order_id: i64,10 pub email: String,11 pub total: i64,12}1314#[listener(queued)]15pub async fn send_receipt(event: Event<OrderPlaced>) -> laravel::Result<()> {16 mail::to(&event.email)17 .send(OrderReceipt {18 order_id: event.order_id,19 })20 .await?;2122 Ok(())23}1use laravel::event::{Event, listener};2use laravel::mail;3use laravel::queue::Queueable;45use crate::mail::OrderReceipt;67#[derive(Event, Queueable)]8pub struct OrderPlaced {9 pub order_id: i64,10 pub email: String,11 pub total: i64,12}1314#[listener(queued)]15pub async fn send_receipt(event: Event<OrderPlaced>) -> laravel::Result<()> {16 mail::to(&event.email)17 .send(OrderReceipt {18 order_id: event.order_id,19 })20 .await?;2122 Ok(())23}
Dispatching the event now pushes a job containing the event so a queue worker executes the listener asynchronously, while any non-queued listeners still run inline. Inside a database transaction, the job is pushed only after the transaction commits, like any queued job.
Queued listeners behave like jobs. After Event<T>, they may accept Inject<T> services, Section<T> config sections, and &Attempt to release, delete, or fail the job. Event fields may also hold models, which the worker reloads from the database before invoking the listener. If a model's row has been deleted by then, the worker deletes the job without invoking the listener, unless the listener has the fail_when_missing_models option.
Queue options
#[listener(queued, ..)] supports all #[job] options (such as queue, tries, backoff, and timeout), as well as connection and delay:
1#[listener(2 queued,3 connection = "redis",4 queue = "emails",5 delay = 10.minutes(),6 tries = 3,7 backoff = 1.minutes(),8)]9pub async fn send_receipt(event: Event<OrderPlaced>) -> laravel::Result<()> {10 // Email the receipt...11 todo!()12}1#[listener(2 queued,3 connection = "redis",4 queue = "emails",5 delay = 10.minutes(),6 tries = 3,7 backoff = 1.minutes(),8)]9pub async fn send_receipt(event: Event<OrderPlaced>) -> laravel::Result<()> {10 // Email the receipt...11 todo!()12}
Laravel identifies the queued job using the listener's module path, such as app::listeners::send_receipt. Before renaming or moving a listener that may still have queued jobs in flight, preserve compatibility by setting name = "app::listeners::send_receipt".
Listener structs
When a queued listener needs additional hooks beyond handle, place #[listener(queued)] on a unit struct's impl block. Implement an async handle function along with any of the optional hooks below (none take self):
| Function | Parameters | Purpose |
|---|---|---|
handle |
Event<T>, plus services, config sections, and &Attempt |
Executes the listener on the worker. |
failed |
Event<T>, &laravel::Error, plus services, config sections, and &Attempt |
Cleans up when the job fails permanently. |
should_queue |
&T |
Returns false to skip queueing the listener for this event. |
middleware |
&T |
Returns job middleware wrapping the listener. |
debounce_id |
&T |
Groups debounced listener runs. |
For example, this listener awards a gift card for orders of $50 or more (total in cents) and logs a warning if all retries fail:
1use laravel::event::{Event, listener};2use laravel::model::create;34use crate::events::OrderPlaced;5use crate::models::GiftCard;67pub struct RewardGiftCard;89#[listener(queued, queue = "rewards", tries = 3)]10impl RewardGiftCard {11 fn should_queue(event: &OrderPlaced) -> bool {12 event.total >= 500013 }1415 async fn handle(event: Event<OrderPlaced>) -> laravel::Result<()> {16 create!(GiftCard {17 order_id: event.order_id,18 amount: 500,19 })20 .await?;2122 Ok(())23 }2425 async fn failed(event: Event<OrderPlaced>, error: &laravel::Error) {26 tracing::warn!(27 order_id = event.order_id,28 %error,29 "Couldn't reward a gift card",30 );31 }32}1use laravel::event::{Event, listener};2use laravel::model::create;34use crate::events::OrderPlaced;5use crate::models::GiftCard;67pub struct RewardGiftCard;89#[listener(queued, queue = "rewards", tries = 3)]10impl RewardGiftCard {11 fn should_queue(event: &OrderPlaced) -> bool {12 event.total >= 500013 }1415 async fn handle(event: Event<OrderPlaced>) -> laravel::Result<()> {16 create!(GiftCard {17 order_id: event.order_id,18 amount: 500,19 })20 .await?;2122 Ok(())23 }2425 async fn failed(event: Event<OrderPlaced>, error: &laravel::Error) {26 tracing::warn!(27 order_id = event.order_id,28 %error,29 "Couldn't reward a gift card",30 );31 }32}
should_queue runs before the job is pushed, so skipped listeners never touch the queue.
Debouncing listeners
When an event fires repeatedly in quick succession, you may want to handle only the final occurrence. For instance, a user saving their profile five times in a minute should receive one confirmation email, not five. Listen for the Updated<User> model event with debounce_for and a debounce_id that groups related events:
1use laravel::event::{Event, listener};2use laravel::mail;3use laravel::model::Updated;45use crate::mail::ProfileUpdated;6use crate::models::User;78pub struct SendProfileUpdatedEmail;910#[listener(queued, debounce_for = 1.minutes())]11impl SendProfileUpdatedEmail {12 fn debounce_id(event: &Updated<User>) -> i64 {13 event.model.id14 }1516 async fn handle(event: Event<Updated<User>>) -> laravel::Result<()> {17 mail::to(&event.model.email)18 .send(ProfileUpdated {19 user: event.model.clone(),20 })21 .await?;2223 Ok(())24 }25}1use laravel::event::{Event, listener};2use laravel::mail;3use laravel::model::Updated;45use crate::mail::ProfileUpdated;6use crate::models::User;78pub struct SendProfileUpdatedEmail;910#[listener(queued, debounce_for = 1.minutes())]11impl SendProfileUpdatedEmail {12 fn debounce_id(event: &Updated<User>) -> i64 {13 event.model.id14 }1516 async fn handle(event: Event<Updated<User>>) -> laravel::Result<()> {17 mail::to(&event.model.email)18 .send(ProfileUpdated {19 user: event.model.clone(),20 })21 .await?;2223 Ok(())24 }25}
Each user now receives a single email one minute after their last update. Without debounce_id, every Updated<User> event would share a single debounce key across all users. To guarantee the listener still runs if a user keeps saving continuously, cap the wait with max_wait, such as #[listener(queued, debounce_for = 1.minutes(), max_wait = 5.minutes())].
Debounced jobs are tracked in your default cache store, so use a shared store like database or redis when running multiple servers. You can learn more about debouncing options in the debounced jobs documentation.
Database transactions
Events dispatched inside a database transaction wait until the outermost transaction commits before running their listeners. If the transaction rolls back, the pending events are discarded so listeners never send receipts or read uncommitted rows. Outside a transaction, dispatch runs listeners immediately. Jobs and broadcasts also wait for transactions to commit.
For example, this version of place_order saves an order and its payment atomically and dispatches OrderPlaced only once both commit:
1use laravel::db;2use laravel::model::create;34use crate::events::OrderPlaced;5use crate::models::{Order, Payment, User};67pub async fn place_order(user: &User, total: i64) -> laravel::Result<Order> {8 let order = db::transaction(async |_| {9 let order = create!(Order {10 user_id: user.id,11 total,12 })13 .await?;1415 create!(Payment {16 order_id: order.id,17 amount: total,18 })19 .await?;2021 OrderPlaced {22 order_id: order.id,23 email: user.email.clone(),24 total,25 }26 .dispatch()27 .await?;2829 Ok(order)30 })31 .await?;3233 Ok(order)34}1use laravel::db;2use laravel::model::create;34use crate::events::OrderPlaced;5use crate::models::{Order, Payment, User};67pub async fn place_order(user: &User, total: i64) -> laravel::Result<Order> {8 let order = db::transaction(async |_| {9 let order = create!(Order {10 user_id: user.id,11 total,12 })13 .await?;1415 create!(Payment {16 order_id: order.id,17 amount: total,18 })19 .await?;2021 OrderPlaced {22 order_id: order.id,23 email: user.email.clone(),24 total,25 }26 .dispatch()27 .await?;2829 Ok(order)30 })31 .await?;3233 Ok(order)34}
Inside the transaction, dispatch returns Ok immediately and defers execution until commit. If a deferred listener fails after commit, db::transaction returns an AfterCommitError while the database changes remain committed. Avoid retrying the transaction, since the order is already saved. You can learn more about handling after-commit failures in the database transactions documentation.
Running listeners in the transaction
Some listeners must participate in the transaction itself, such as reserving inventory that should succeed or roll back alongside the order. Annotate those listeners with #[listener(at_dispatch)] so they run immediately when dispatch is called instead of waiting for commit:
1use laravel::event::{Event, listener};2use laravel::model::create;34use crate::events::OrderPlaced;5use crate::models::Reservation;67#[listener(at_dispatch)]8pub async fn reserve_stock(event: Event<OrderPlaced>) -> laravel::Result<()> {9 create!(Reservation {10 order_id: event.order_id,11 })12 .await?;1314 Ok(())15}1use laravel::event::{Event, listener};2use laravel::model::create;34use crate::events::OrderPlaced;5use crate::models::Reservation;67#[listener(at_dispatch)]8pub async fn reserve_stock(event: Event<OrderPlaced>) -> laravel::Result<()> {9 create!(Reservation {10 order_id: event.order_id,11 })12 .await?;1314 Ok(())15}
Because dispatch runs at_dispatch listeners before returning, their database writes commit or roll back with the enclosing transaction, and propagating an error with ? rolls the transaction back. All other listeners for the event still wait for commit. Keep at_dispatch listeners fast, since the transaction holds its row locks while they execute.
To run every listener of an event at dispatch time, mark the event struct with #[event(at_dispatch)]. When registering a listener manually in with_events, call events.listen_at_dispatch(reserve_stock).
Testing events
When testing code that dispatches events, you typically want to assert that the expected event was dispatched while testing listeners separately. Call event::fake() to record dispatched events without executing their listeners, then run assertions on the returned fake:
1use laravel::event;2use laravel::model::create;3use laravel::testing::prelude::*;4use serde_json::json;56use app::events::OrderPlaced;7use app::models::User;89#[laravel::test]10async fn placing_an_order_dispatches_an_event(app: Application) -> laravel::Result<()> {11 let user = create!(User {12 name: "Taylor",14 password: "password",15 })16 .await?;1718 let events = event::fake();1920 app.post("/orders")21 .acting_as(&user)22 .json(json!({ "total": 2500 }))23 .await24 .assert_created();2526 events.assert_dispatched::<OrderPlaced>();2728 events.assert_dispatched_where::<OrderPlaced>(|event| {30 });3132 events.assert_dispatched_times::<OrderPlaced>(1);3334 Ok(())35}1use laravel::event;2use laravel::model::create;3use laravel::testing::prelude::*;4use serde_json::json;56use app::events::OrderPlaced;7use app::models::User;89#[laravel::test]10async fn placing_an_order_dispatches_an_event(app: Application) -> laravel::Result<()> {11 let user = create!(User {12 name: "Taylor",14 password: "password",15 })16 .await?;1718 let events = event::fake();1920 app.post("/orders")21 .acting_as(&user)22 .json(json!({ "total": 2500 }))23 .await24 .assert_created();2526 events.assert_dispatched::<OrderPlaced>();2728 events.assert_dispatched_where::<OrderPlaced>(|event| {30 });3132 events.assert_dispatched_times::<OrderPlaced>(1);3334 Ok(())35}
You may also call assert_not_dispatched::<T>(), assert_not_dispatched_where, and assert_nothing_dispatched(). To inspect recorded events directly, events.dispatched::<OrderPlaced>() returns them in dispatch order.
The fake stays active for the lifetime of its handle; dropping the handle restores normal event dispatch. Each test application maintains an isolated fake, so concurrent tests never see each other's events.
Faking selected events
To fake only specific events while allowing all other events to run their listeners normally, chain .only::<T>() before exercising your application:
1let events = event::fake()2 .only::<OrderPlaced>()3 .only::<OrderCancelled>();1let events = event::fake()2 .only::<OrderPlaced>()3 .only::<OrderCancelled>();
To fake every event except specific ones, chain .except::<T>(), such as event::fake().except::<OrderShipped>().
Testing a listener
To test a single listener in isolation without running other listeners for the same event, pass the listener and event instance to app.listener. The listener resolves its injected services normally, so swapped fakes and helpers like the mail fake work as expected:
1use laravel::mail;2use laravel::testing::prelude::*;34use app::events::OrderPlaced;5use app::listeners::send_receipt;6use app::mail::OrderReceipt;78#[laravel::test]9async fn customers_get_a_receipt(app: Application) -> laravel::Result<()> {10 let mail = mail::fake();1112 app.listener(13 send_receipt,14 OrderPlaced {15 order_id: 42,17 total: 2500,18 },19 )20 .await?;212324 Ok(())25}1use laravel::mail;2use laravel::testing::prelude::*;34use app::events::OrderPlaced;5use app::listeners::send_receipt;6use app::mail::OrderReceipt;78#[laravel::test]9async fn customers_get_a_receipt(app: Application) -> laravel::Result<()> {10 let mail = mail::fake();1112 app.listener(13 send_receipt,14 OrderPlaced {15 order_id: 42,17 total: 2500,18 },19 )20 .await?;212324 Ok(())25}
app.listener returns any error produced by the listener. For a queued listener, app.listener pushes its job onto the queue; because tests use the sync queue connection even when a listener specifies a custom connection, the job executes before app.listener returns.
Testing queued listeners
A queued listener pushes a Queued<L> job that dereferences to the event. To verify that dispatching an event queued the listener, use the queue fake:
1use laravel::event::Queued;2use laravel::model::create;3use laravel::queue;4use laravel::testing::prelude::*;5use serde_json::json;67use app::listeners::send_receipt;8use app::models::User;910#[laravel::test]11async fn placing_an_order_queues_the_receipt(app: Application) -> laravel::Result<()> {12 let user = create!(User {13 name: "Taylor",15 password: "password",16 })17 .await?;1819 let queue = queue::fake();2021 app.post("/orders")22 .acting_as(&user)23 .json(json!({ "total": 2500 }))24 .await25 .assert_created();2627 queue.assert_pushed_where::<Queued<send_receipt>>(|job| {29 });3031 Ok(())32}1use laravel::event::Queued;2use laravel::model::create;3use laravel::queue;4use laravel::testing::prelude::*;5use serde_json::json;67use app::listeners::send_receipt;8use app::models::User;910#[laravel::test]11async fn placing_an_order_queues_the_receipt(app: Application) -> laravel::Result<()> {12 let user = create!(User {13 name: "Taylor",15 password: "password",16 })17 .await?;1819 let queue = queue::fake();2021 app.post("/orders")22 .acting_as(&user)23 .json(json!({ "total": 2500 }))24 .await25 .assert_created();2627 queue.assert_pushed_where::<Queued<send_receipt>>(|job| {29 });3031 Ok(())32}
Because event::fake() prevents listeners from running at all, nothing reaches the queue when both are active. Use queue::fake() on its own when testing queued listeners.
To test how a single job attempt behaves (such as a release or failure), run the queued listener job directly with app.job:
1app.job(Queued::<send_receipt>::new(OrderPlaced {2 order_id: 42,4 total: 2500,5}))6.await7.assert_succeeded();1app.job(Queued::<send_receipt>::new(OrderPlaced {2 order_id: 42,4 total: 2500,5}))6.await7.assert_succeeded();