Skip to content
Digging Deeper

Broadcasting

Introduction

In many modern web applications, WebSockets power realtime, live-updating user interfaces. When an order ships, a deploy finishes, or a teammate joins a room, your application can broadcast its events to the browser over a WebSocket connection instead of having the page poll your server for changes.

Imagine a customer keeping their order page open while the warehouse packs their shipment. When the order ships, your application dispatches an OrderShipped event, and its listeners email the tracking number. With broadcasting, the same event also reaches the customer's browser so the page displays the tracking number without a refresh.

Laravel publishes broadcast events to a Reverb server, which maintains your users' WebSocket connections. Each event is published to one or more named channels, and each page subscribes to the channels it needs using Laravel Echo or Inertia's live props. Anyone may subscribe to a public channel. Your application authorizes subscriptions to private channels and presence channels, where presence channels also inform subscribers who else is currently subscribed.

Configuration

The BROADCAST_CONNECTION environment variable controls how Laravel publishes broadcasts:

Connection Behavior
reverb Publishes events to a Reverb server.
log Writes each broadcast's event name, channels, and payload to the log instead of publishing. New applications use this for local development.
discard Drops all broadcasts without logging. Selected when BROADCAST_CONNECTION is unset or empty.

To broadcast events to a browser on your machine, you need a running Reverb server. For local development, Laravel includes one behind the reverb feature. Add reverb to the features your application already enables for laravel-rust in Cargo.toml:

1[dependencies]
2laravel-rust = { version = "0.1", features = ["database-postgres", "redis", "sqs", "reverb"] }
1[dependencies]
2laravel-rust = { version = "0.1", features = ["database-postgres", "redis", "sqs", "reverb"] }

Next, switch BROADCAST_CONNECTION to reverb and choose credentials in your .env file. The local Reverb server reads the same REVERB_APP_ID, REVERB_APP_KEY, and REVERB_APP_SECRET variables as the reverb broadcast connection, so values like these work for local development without extra setup:

1BROADCAST_CONNECTION=reverb
2REVERB_APP_ID=my-app
3REVERB_APP_KEY=my-key
4REVERB_APP_SECRET=my-secret
5REVERB_HOST=localhost
6REVERB_PORT=8080
7REVERB_SCHEME=http
1BROADCAST_CONNECTION=reverb
2REVERB_APP_ID=my-app
3REVERB_APP_KEY=my-key
4REVERB_APP_SECRET=my-secret
5REVERB_HOST=localhost
6REVERB_PORT=8080
7REVERB_SCHEME=http

Keep REVERB_APP_SECRET on the server. The browser only needs the application key.

Start the local Reverb server with the reverb:start command:

1laravel reverb:start
1laravel reverb:start

To learn more about configuring and running the local server, check out the WebSockets guide. In production, use Laravel Cloud's managed Reverb server instead of running reverb:start.

Laravel delivers broadcasts through your queue. For events to reach the browser locally, your application, a queue worker, and laravel reverb:start all need to be running. Because laravel dev starts your application, queue worker, and Vite, run laravel reverb:start in a separate terminal alongside laravel dev. You may choose a dedicated queue connection or queue name using BROADCAST_QUEUE_CONNECTION and BROADCAST_QUEUE, which default to your application's default queue connection and queue. If a broadcast needs to reach browsers without waiting for a worker, you may publish it immediately.

Broadcasting events

Any event can be broadcast by listing its channels in the #[event(broadcast(..))] attribute. For example, this OrderShipped event broadcasts on a private channel for its order:

1use laravel::event::Event;
2 
3#[derive(Event)]
4#[event(broadcast(private = "orders.{order_id}"))]
5pub struct OrderShipped {
6 pub order_id: i64,
7 pub tracking_number: String,
8 pub(crate) internal_note: String,
9}
1use laravel::event::Event;
2 
3#[derive(Event)]
4#[event(broadcast(private = "orders.{order_id}"))]
5pub struct OrderShipped {
6 pub order_id: i64,
7 pub tracking_number: String,
8 pub(crate) internal_note: String,
9}

Dispatch the event as you normally would, for example from the handler that marks the order as shipped:

1use crate::events::OrderShipped;
2 
3OrderShipped {
4 order_id: 42,
5 tracking_number: "TRACK-123".into(),
6 internal_note: "Packed by warehouse B".into(),
7}
8.dispatch()
9.await?;
1use crate::events::OrderShipped;
2 
3OrderShipped {
4 order_id: 42,
5 tracking_number: "TRACK-123".into(),
6 internal_note: "Packed by warehouse B".into(),
7}
8.dispatch()
9.await?;

This publishes an OrderShipped event to the private-orders.42 channel with order_id and tracking_number in its payload. Any listeners registered for the event still run as usual.

Channels

Use public, private, or presence to choose each channel's visibility, and repeat them to broadcast on multiple channels. Each {field} placeholder is replaced with the value of that field on the event, including private fields. A model field formats as its route key so your channel authorization callback can bind the model again:

1use laravel::event::Event;
2 
3use crate::models::Order;
4 
5#[derive(Event)]
6#[event(broadcast(
7 name = "order.shipped",
8 private = "orders.{order}",
9 private = "users.{user_id}",
10 public = "shipping",
11))]
12pub struct OrderShipped {
13 pub order: Order,
14 pub user_id: i64,
15}
1use laravel::event::Event;
2 
3use crate::models::Order;
4 
5#[derive(Event)]
6#[event(broadcast(
7 name = "order.shipped",
8 private = "orders.{order}",
9 private = "users.{user_id}",
10 public = "shipping",
11))]
12pub struct OrderShipped {
13 pub order: Order,
14 pub user_id: i64,
15}

Use private channels for user-specific or order-specific updates, since anyone can subscribe to a public channel.

By default, an event broadcasts under its struct name (like OrderShipped). You may override this with the name option. When listening for events in Echo, prefix any custom name containing dots with a leading dot (for example, '.order.shipped').

The payload

Laravel builds the broadcast payload from the event's pub fields and omits private and pub(crate) fields. Every pub field included in the payload must implement Serialize. You may also rename or exclude individual pub fields using attributes:

1use laravel::event::Event;
2 
3#[derive(Event)]
4#[event(broadcast(private = "orders.{order_id}"))]
5pub struct OrderShipped {
6 pub order_id: i64,
7 #[event(rename = "trackingNumber")]
8 pub tracking_number: String,
9 #[event(skip)]
10 pub warehouse: String,
11 pub(crate) internal_note: String,
12}
1use laravel::event::Event;
2 
3#[derive(Event)]
4#[event(broadcast(private = "orders.{order_id}"))]
5pub struct OrderShipped {
6 pub order_id: i64,
7 #[event(rename = "trackingNumber")]
8 pub tracking_number: String,
9 #[event(skip)]
10 pub warehouse: String,
11 pub(crate) internal_note: String,
12}

In this example, order_id and trackingNumber are sent to the browser, while warehouse and internal_note are omitted.

Every subscriber on the channel receives the same payload, so only include data that every authorized subscriber is allowed to see.

Custom broadcasts

When the attribute isn't flexible enough, for example when you need a custom payload shape or want to broadcast only under certain conditions, mark the event with #[event(broadcast)] and implement the Broadcast trait. Implement broadcast_on to return the channels, and optionally implement broadcast_with for the payload, broadcast_as for the event name, and broadcast_when to conditionally skip broadcasting:

1use laravel::broadcast::{Broadcast, Channel};
2use laravel::event::Event;
3use serde_json::{Value, json};
4 
5#[derive(Event)]
6#[event(broadcast)]
7pub struct OrderUpdated {
8 pub order_id: i64,
9 pub status: String,
10 notify: bool,
11}
12 
13impl Broadcast for OrderUpdated {
14 fn broadcast_on(&self) -> laravel::Result<Vec<Channel>> {
15 Ok(vec![Channel::private(format!("orders.{}", self.order_id))?])
16 }
17 
18 fn broadcast_with(&self) -> laravel::Result<Value> {
19 Ok(json!({ "id": self.order_id, "status": self.status }))
20 }
21 
22 fn broadcast_when(&self) -> bool {
23 self.notify
24 }
25}
1use laravel::broadcast::{Broadcast, Channel};
2use laravel::event::Event;
3use serde_json::{Value, json};
4 
5#[derive(Event)]
6#[event(broadcast)]
7pub struct OrderUpdated {
8 pub order_id: i64,
9 pub status: String,
10 notify: bool,
11}
12 
13impl Broadcast for OrderUpdated {
14 fn broadcast_on(&self) -> laravel::Result<Vec<Channel>> {
15 Ok(vec![Channel::private(format!("orders.{}", self.order_id))?])
16 }
17 
18 fn broadcast_with(&self) -> laravel::Result<Value> {
19 Ok(json!({ "id": self.order_id, "status": self.status }))
20 }
21 
22 fn broadcast_when(&self) -> bool {
23 self.notify
24 }
25}

broadcast_with must return a JSON object. When broadcast_when returns false, Laravel skips the broadcast while still running the event's listeners. To push updated values to Inertia's live props, implement broadcast_props as covered in the Inertia guide.

Authorizing subscriptions

Before a browser can subscribe to a private or presence channel, Echo sends an authorization request to your application to verify that the current user may listen. New applications register their channels in src/routes/channels.rs, which src/app.rs passes to routing.channels to serve Echo's requests at POST /broadcasting/auth. Each channel pairs a pattern with an authorization callback that accepts the same arguments as a handler, including Authenticated<User>, Auth<User>, Inject<T>, Params, and models.

For example, suppose your application has an Order model and each user has a team_id column. The following channel definitions allow signed-in users to subscribe to their own orders and to their team's presence channel:

1use laravel::broadcast::{Channels, Member};
2use laravel::prelude::*;
3use serde_json::json;
4 
5use crate::models::{Order, User};
6 
7pub fn routes(channel: &mut Channels) {
8 channel.private("orders.{order}", order);
9 channel.presence("teams.{team}", team);
10}
11 
12async fn order(order: Order, user: Authenticated<User>) -> bool {
13 order.user_id == user.id
14}
15 
16async fn team(Params(team): Params<i64>, user: Authenticated<User>) -> laravel::Result<Option<Member>> {
17 if user.team_id != team {
18 return Ok(None);
19 }
20 
21 Ok(Some(Member::new(
22 user.id.to_string(),
23 json!({ "id": user.id, "name": user.name }),
24 )?))
25}
1use laravel::broadcast::{Channels, Member};
2use laravel::prelude::*;
3use serde_json::json;
4 
5use crate::models::{Order, User};
6 
7pub fn routes(channel: &mut Channels) {
8 channel.private("orders.{order}", order);
9 channel.presence("teams.{team}", team);
10}
11 
12async fn order(order: Order, user: Authenticated<User>) -> bool {
13 order.user_id == user.id
14}
15 
16async fn team(Params(team): Params<i64>, user: Authenticated<User>) -> laravel::Result<Option<Member>> {
17 if user.team_id != team {
18 return Ok(None);
19 }
20 
21 Ok(Some(Member::new(
22 user.id.to_string(),
23 json!({ "id": user.id, "name": user.name }),
24 )?))
25}

Extracting Authenticated<User> denies guests with a 403 response automatically without calling your callback or redirecting to a login page. If a channel needs to inspect optional authentication state instead, extract Auth<User>.

A private channel callback returns true to authorize the subscription or false to deny it. A presence channel callback returns Some(Member) with the member data visible to other subscribers on the channel, or None to deny the subscription. Only include member fields that every subscriber on the channel may see.

Channel patterns omit the private- or presence- prefix, and each {parameter} matches a single dot-separated segment. Browsers cannot subscribe to any private or presence channel that has not been registered.

Callbacks bind models like handlers do, matching each route parameter by name so order: Order reads {order}. As with nested routes, teams.{team}.orders.{order} scopes the order to that team. If no matching row exists or a parameter fails to parse, Laravel rejects the subscription with a 403 response without calling your callback:

1use laravel::broadcast::Channels;
2use laravel::prelude::*;
3 
4use crate::models::{Order, Team, User};
5 
6pub fn routes(channel: &mut Channels) {
7 channel.private("teams.{team}.orders.{order}", team_order);
8}
9 
10async fn team_order(team: Team, order: Order, user: Authenticated<User>) -> bool {
11 user.team_id == team.id && order.user_id == user.id
12}
1use laravel::broadcast::Channels;
2use laravel::prelude::*;
3 
4use crate::models::{Order, Team, User};
5 
6pub fn routes(channel: &mut Channels) {
7 channel.private("teams.{team}.orders.{order}", team_order);
8}
9 
10async fn team_order(team: Team, order: Order, user: Authenticated<User>) -> bool {
11 user.team_id == team.id && order.user_id == user.id
12}

New applications include a sample example-channel in src/routes/channels.rs that returns true; replace it with your own channels.

Registering a channel does not require authentication on its own. A callback that returns true without checking the user allows guests to subscribe as well.

Receiving broadcasts

In the browser, Laravel Echo subscribes to channels and listens for events. Echo provides React hooks that integrate cleanly with Laravel's React frontend.

If a page only needs to reload or update its Inertia props when an event arrives, use live props instead of writing Echo listeners by hand.

Installing Echo

Reverb speaks the Pusher protocol, so install Echo's React package alongside laravel-echo and pusher-js:

1npm install @laravel/echo-react laravel-echo pusher-js
1npm install @laravel/echo-react laravel-echo pusher-js

Echo reads the Reverb server's address from Vite's environment variables. Your application's .env file exposes these values to Vite so the browser can connect (sharing only the application key, never the secret):

1VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
2VITE_REVERB_HOST="${REVERB_HOST}"
3VITE_REVERB_PORT="${REVERB_PORT}"
4VITE_REVERB_SCHEME="${REVERB_SCHEME}"
1VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
2VITE_REVERB_HOST="${REVERB_HOST}"
3VITE_REVERB_PORT="${REVERB_PORT}"
4VITE_REVERB_SCHEME="${REVERB_SCHEME}"

Next, configure Echo once at the top of resources/js/app.tsx:

1import { configureEcho } from '@laravel/echo-react';
2 
3configureEcho({
4 broadcaster: 'reverb',
5 namespace: false,
6});
1import { configureEcho } from '@laravel/echo-react';
2 
3configureEcho({
4 broadcaster: 'reverb',
5 namespace: false,
6});

By default, Echo prefixes event names with App.Events, which Laravel Rust's events do not use. Setting namespace: false disables that prefix so you can listen for events by the exact name they broadcast with, like 'OrderShipped'.

Finally, rebuild your assets with npm run build, or run laravel dev during local development.

Listening for events

Call useEcho in a component with the channel name, event name, and a callback. Echo authorizes the private channel subscription automatically and leaves the channel when the component unmounts:

1import { useEcho } from '@laravel/echo-react';
2 
3export function OrderStatus({ order }) {
4 useEcho(`orders.${order.id}`, 'OrderShipped', (event) => {
5 console.log(event.tracking_number);
6 });
7 
8 // ...
9}
1import { useEcho } from '@laravel/echo-react';
2 
3export function OrderStatus({ order }) {
4 useEcho(`orders.${order.id}`, 'OrderShipped', (event) => {
5 console.log(event.tracking_number);
6 });
7 
8 // ...
9}

The callback receives the event's payload. To listen for multiple events on the same channel, pass an array of event names:

1useEcho(`orders.${order.id}`, ['OrderShipped', 'OrderCancelled'], (event) => {
2 console.log(event.order_id);
3});
1useEcho(`orders.${order.id}`, ['OrderShipped', 'OrderCancelled'], (event) => {
2 console.log(event.order_id);
3});

In TypeScript, pass a type parameter to type the event payload:

1type OrderShippedPayload = {
2 order_id: number;
3 tracking_number: string;
4};
5 
6useEcho<OrderShippedPayload>(`orders.${order.id}`, 'OrderShipped', (event) => {
7 console.log(event.tracking_number);
8});
1type OrderShippedPayload = {
2 order_id: number;
3 tracking_number: string;
4};
5 
6useEcho<OrderShippedPayload>(`orders.${order.id}`, 'OrderShipped', (event) => {
7 console.log(event.tracking_number);
8});

useEcho also returns helpers to pause listening, resume listening, or leave the channel early:

1const { stopListening, listen, leaveChannel } = useEcho(
2 `orders.${order.id}`,
3 'OrderShipped',
4 (event) => {
5 console.log(event.tracking_number);
6 },
7);
8 
9// Stop listening without leaving the channel...
10stopListening();
11 
12// Start listening again...
13listen();
14 
15// Leave the channel...
16leaveChannel();
1const { stopListening, listen, leaveChannel } = useEcho(
2 `orders.${order.id}`,
3 'OrderShipped',
4 (event) => {
5 console.log(event.tracking_number);
6 },
7);
8 
9// Stop listening without leaving the channel...
10stopListening();
11 
12// Start listening again...
13listen();
14 
15// Leave the channel...
16leaveChannel();

Even with namespace: false, Echo converts dots inside an event name into backslashes. Prefix any event name that contains dots with a leading dot (for example, '.order.shipped' or '.export.progress') so Echo uses the name as written.

Public and presence channels

useEcho subscribes to private channels by default. To subscribe to a public channel, use useEchoPublic:

1import { useEchoPublic } from '@laravel/echo-react';
2 
3useEchoPublic('deploys', 'DeployFinished', (event) => {
4 console.log(event.environment);
5});
1import { useEchoPublic } from '@laravel/echo-react';
2 
3useEchoPublic('deploys', 'DeployFinished', (event) => {
4 console.log(event.environment);
5});

Presence channels also track who is currently subscribed. Subscribe with useEchoPresence, then attach here, joining, and leaving callbacks to the channel. here receives the list of members already present, while joining and leaving receive a single member as users arrive or depart. Each member object matches the Member payload returned by your channel authorization callback:

1import { useEffect, useState } from 'react';
2import { useEchoPresence } from '@laravel/echo-react';
3 
4export function TeamMembers({ team }) {
5 const [members, setMembers] = useState([]);
6 const { channel } = useEchoPresence(`teams.${team.id}`);
7 
8 useEffect(() => {
9 channel()
10 ?.here((members) => setMembers(members))
11 .joining((member) => setMembers((members) => [...members, member]))
12 .leaving((member) =>
13 setMembers((members) =>
14 members.filter((other) => other.id !== member.id),
15 ),
16 );
17 }, [channel]);
18 
19 return members.map((member) => <span key={member.id}>{member.name}</span>);
20}
1import { useEffect, useState } from 'react';
2import { useEchoPresence } from '@laravel/echo-react';
3 
4export function TeamMembers({ team }) {
5 const [members, setMembers] = useState([]);
6 const { channel } = useEchoPresence(`teams.${team.id}`);
7 
8 useEffect(() => {
9 channel()
10 ?.here((members) => setMembers(members))
11 .joining((member) => setMembers((members) => [...members, member]))
12 .leaving((member) =>
13 setMembers((members) =>
14 members.filter((other) => other.id !== member.id),
15 ),
16 );
17 }, [channel]);
18 
19 return members.map((member) => <span key={member.id}>{member.name}</span>);
20}

Client events

Sometimes a browser needs to notify other browsers directly without hitting your application server, such as showing a "typing" indicator. Send client events through Reverb with whisper and receive them with listenForWhisper. Client events work on private and presence channels:

1import { useEffect } from 'react';
2import { useEchoPresence } from '@laravel/echo-react';
3 
4export function MessageBox({ team, user }) {
5 const { channel } = useEchoPresence(`teams.${team.id}`);
6 
7 useEffect(() => {
8 channel()?.listenForWhisper('typing', (event) => {
9 console.log(`${event.name} is typing...`);
10 });
11 }, [channel]);
12 
13 const typing = () => channel()?.whisper('typing', { name: user.name });
14 
15 return <textarea onChange={typing} />;
16}
1import { useEffect } from 'react';
2import { useEchoPresence } from '@laravel/echo-react';
3 
4export function MessageBox({ team, user }) {
5 const { channel } = useEchoPresence(`teams.${team.id}`);
6 
7 useEffect(() => {
8 channel()?.listenForWhisper('typing', (event) => {
9 console.log(`${event.name} is typing...`);
10 });
11 }, [channel]);
12 
13 const typing = () => channel()?.whisper('typing', { name: user.name });
14 
15 return <textarea onChange={typing} />;
16}

Connection status

To display whether the browser is connected to Reverb, call useConnectionStatus. It returns connected, connecting, reconnecting, disconnected, or failed:

1import { useConnectionStatus } from '@laravel/echo-react';
2 
3export function ConnectionIndicator() {
4 const status = useConnectionStatus();
5 
6 return <div>Connection: {status}</div>;
7}
1import { useConnectionStatus } from '@laravel/echo-react';
2 
3export function ConnectionIndicator() {
4 const status = useConnectionStatus();
5 
6 return <div>Connection: {status}</div>;
7}

Dispatch options

Often, the browser that triggered an action already reflects the change and doesn't need to receive the broadcast. To exclude the current user's browser tab, dispatch the event with broadcast::event and call to_others:

1use laravel::broadcast;
2 
3use crate::events::OrderShipped;
4 
5broadcast::event(OrderShipped {
6 order_id: 42,
7 tracking_number: "TRACK-123".into(),
8 internal_note: "Packed by warehouse B".into(),
9})
10.to_others()
11.await?;
1use laravel::broadcast;
2 
3use crate::events::OrderShipped;
4 
5broadcast::event(OrderShipped {
6 order_id: 42,
7 tracking_number: "TRACK-123".into(),
8 internal_note: "Packed by warehouse B".into(),
9})
10.to_others()
11.await?;

to_others reads the socket ID from the request's X-Socket-ID header and excludes only that browser tab, leaving the user's other open tabs subscribed. If the request does not include a socket ID, to_others broadcasts to everyone.

To send the X-Socket-ID header automatically on every Inertia request (including pages without a live prop), register a socket ID resolver alongside configureEcho in resources/js/app.tsx:

1import { socketId } from '@inertiajs/react';
2import { configureEcho, echo } from '@laravel/echo-react';
3 
4configureEcho({
5 broadcaster: 'reverb',
6 namespace: false,
7});
8 
9socketId.resolveUsing(() => echo().socketId());
1import { socketId } from '@inertiajs/react';
2import { configureEcho, echo } from '@laravel/echo-react';
3 
4configureEcho({
5 broadcaster: 'reverb',
6 namespace: false,
7});
8 
9socketId.resolveUsing(() => echo().socketId());

When making requests with fetch, read the socket ID from Echo's useSocketId hook and pass it in the X-Socket-ID header. Outside a request (for example, inside a queued job), you may exclude a specific socket directly with except_socket("123.456").

broadcast::event dispatches the event and runs its listeners like dispatch, with these additional options:

Method Effect
to_others() Excludes the browser tab that sent the current request.
except_socket(id) Excludes the given socket ID.
via(name) Publishes through the named broadcast connection.
on_connection(name), on_queue(name) Delivers the broadcast through the given queue connection or queue.

One-off broadcasts

Some messages don't warrant a dedicated event struct, such as progress updates from a long-running export. You may publish directly to a channel by passing an event name and payload. For example, a job exporting a report can broadcast its progress using its export_id:

1use laravel::broadcast;
2use serde_json::json;
3 
4broadcast::private(format!("exports.{export_id}"))
5 .send("export.progress", json!({ "percent": 75 }))
6 .await?;
1use laravel::broadcast;
2use serde_json::json;
3 
4broadcast::private(format!("exports.{export_id}"))
5 .send("export.progress", json!({ "percent": 75 }))
6 .await?;

broadcast::public, broadcast::private, and broadcast::presence take the channel name without its prefix. send delivers through the queue as broadcast events do, while send_now publishes immediately. Both support all of the dispatch options. Because the event name above contains dots, listen for it in Echo with a leading dot: '.export.progress'.

One-off broadcasts do not dispatch an application event, so no listeners run.

Queues and transactions

Dispatching a broadcast event prepares its channels and payload, then pushes a job onto your queue to publish them. If Reverb is temporarily unreachable, the job retries automatically. If Reverb rejects the broadcast (for example, due to an invalid REVERB_APP_SECRET), the job fails immediately with Reverb's error message. Inside a database transaction, the broadcast waits until the transaction commits, and a rollback discards it so browsers never receive updates for rolled-back data.

To publish without using the queue, add immediately to the broadcast attribute. Dispatching then publishes right away and returns any Reverb error directly. Inside a transaction, the broadcast still waits for the commit, and db::transaction returns any publish failure as an AfterCommitError:

1use laravel::event::Event;
2 
3#[derive(Event)]
4#[event(broadcast(public = "orders", immediately))]
5pub struct OrderShipped {
6 pub order_id: i64,
7}
1use laravel::event::Event;
2 
3#[derive(Event)]
4#[event(broadcast(public = "orders", immediately))]
5pub struct OrderShipped {
6 pub order_id: i64,
7}

Most applications should leave broadcasting on the queue so a Reverb outage doesn't fail incoming requests. Reach for immediately only when an update must reach browsers without waiting for a queue worker.

Testing

Call broadcast::fake() in a test to record broadcasts in memory instead of publishing them. The event's listeners still run as normal:

1use laravel::broadcast;
2use laravel::testing::prelude::*;
3 
4use crate::events::OrderShipped;
5 
6#[laravel::test]
7async fn shipping_an_order_broadcasts_it(_app: Application) -> laravel::Result<()> {
8 let broadcasts = broadcast::fake();
9 
10 OrderShipped {
11 order_id: 42,
12 tracking_number: "TRACK-123".into(),
13 internal_note: "Packed by warehouse B".into(),
14 }
15 .dispatch()
16 .await?;
17 
18 broadcasts.assert_broadcasted_where::<OrderShipped>(|event| {
19 event.channels == ["private-orders.42"]
20 && event.payload["tracking_number"] == "TRACK-123"
21 && event.payload.get("internal_note").is_none()
22 });
23 
24 Ok(())
25}
1use laravel::broadcast;
2use laravel::testing::prelude::*;
3 
4use crate::events::OrderShipped;
5 
6#[laravel::test]
7async fn shipping_an_order_broadcasts_it(_app: Application) -> laravel::Result<()> {
8 let broadcasts = broadcast::fake();
9 
10 OrderShipped {
11 order_id: 42,
12 tracking_number: "TRACK-123".into(),
13 internal_note: "Packed by warehouse B".into(),
14 }
15 .dispatch()
16 .await?;
17 
18 broadcasts.assert_broadcasted_where::<OrderShipped>(|event| {
19 event.channels == ["private-orders.42"]
20 && event.payload["tracking_number"] == "TRACK-123"
21 && event.payload.get("internal_note").is_none()
22 });
23 
24 Ok(())
25}

The broadcast fake also provides assert_broadcasted, assert_broadcasted_times, assert_not_broadcasted, and assert_nothing_broadcasted. To inspect a one-off broadcast, look it up by event name:

1use serde_json::json;
2 
3let records = broadcasts.broadcast_named("export.progress");
4 
5assert_eq!(records[0].channels, ["private-exports.42"]);
6assert_eq!(records[0].payload, json!({ "percent": 75 }));
1use serde_json::json;
2 
3let records = broadcasts.broadcast_named("export.progress");
4 
5assert_eq!(records[0].channels, ["private-exports.42"]);
6assert_eq!(records[0].payload, json!({ "percent": 75 }));

An event fake records the event without broadcasting it, so use broadcast::fake() on its own when testing broadcasts.