Broadcasting
- Introduction
- Configuration
- Broadcasting events
- Authorizing subscriptions
- Receiving broadcasts
- Dispatch options
- One-off broadcasts
- Queues and transactions
- Testing
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. |
Only a Reverb server can sign subscriptions, so with log or discard, Laravel refuses every subscription to a private or presence channel with a 403, even when your callback allows it. To try private channels in the browser, run Reverb locally and switch to the reverb connection.
To broadcast events to a browser on your machine, you need a running Reverb server. Laravel includes a local Reverb server through the reverb:start command. First, 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 such as these work for local development without extra setup:
BROADCAST_CONNECTION=reverb
REVERB_APP_ID=my-app
REVERB_APP_KEY=my-key
REVERB_APP_SECRET=my-secret
REVERB_HOST=localhost
REVERB_PORT=8080
REVERB_SCHEME=httpKeep REVERB_APP_SECRET on the server. The browser only needs the application key.
Start the local Reverb server with the reverb:start command:
laravel reverb:startTo 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 giving it a BroadcastOn method that returns its channels. For example, this OrderShipped event in your application's events package broadcasts on a private channel for its order:
package events
import (
"fmt"
"go.laravel.com/broadcast"
)
type OrderShipped struct {
OrderID int64 `json:"order_id"`
TrackingNumber string `json:"tracking_number"`
InternalNote string `json:"-"`
}
func (e OrderShipped) BroadcastOn() []broadcast.Channel {
return []broadcast.Channel{broadcast.Private(fmt.Sprintf("orders.%d", e.OrderID))}
}Dispatch the event as you normally would, such as from the handler that marks the order as shipped:
package orders
import (
"go.laravel.com/event"
"go.laravel.com/web"
"app/events"
)
func Ship(r *web.Request) *web.Response {
// Ship the order...
err := event.Dispatch(r, events.OrderShipped{
OrderID: 42,
TrackingNumber: "TRACK-123",
InternalNote: "Packed by warehouse B",
})
if err != nil {
return web.Fail(err)
}
return web.NoContent()
}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. Laravel broadcasts the event before it runs the listeners, and a failed broadcast doesn't stop them, so a Reverb outage doesn't cost the customer their tracking email. event.Dispatch still returns the broadcast's error, joined with any listener's.
Channels
Use broadcast.Public, broadcast.Private, or broadcast.Presence to choose each channel's visibility. Each takes the channel's name without the private- or presence- prefix. To broadcast on multiple channels, such as the order's own channel, its customer's channel, and a public shipping board, return each of them:
type OrderShipped struct {
OrderID int64 `json:"order_id"`
UserID int64 `json:"user_id"`
}
func (e OrderShipped) BroadcastOn() []broadcast.Channel {
return []broadcast.Channel{
broadcast.Private(fmt.Sprintf("orders.%d", e.OrderID)),
broadcast.Private(fmt.Sprintf("users.%d", e.UserID)),
broadcast.Public("shipping"),
}
}Use private channels for user-specific or order-specific updates, since anyone can subscribe to a public channel. Separate the parts of a channel's name with dots, as in orders.42, since a name may only contain letters, digits, and _ - = @ , . ;.
The payload
Laravel builds the broadcast payload from the event's JSON encoding, so the event's json tags decide what the browser receives. A tag renames a field, json:"-" omits it, and unexported fields are never sent:
type OrderShipped struct {
OrderID int64 `json:"order_id"`
TrackingNumber string `json:"trackingNumber"`
Warehouse string `json:"-"`
internalNote string
}In this example, order_id and trackingNumber are sent to the browser, while Warehouse and internalNote 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
Sometimes the event's fields aren't the right payload, such as when you need a custom payload shape or want to broadcast only under certain conditions. Laravel looks for a few optional methods on the event: BroadcastWith returns the payload, BroadcastAs returns the event name, and BroadcastWhen returns false to skip broadcasting:
package events
import (
"fmt"
"go.laravel.com/broadcast"
)
type OrderUpdated struct {
OrderID int64
Status string
Notify bool
}
func (e OrderUpdated) BroadcastOn() []broadcast.Channel {
return []broadcast.Channel{broadcast.Private(fmt.Sprintf("orders.%d", e.OrderID))}
}
func (e OrderUpdated) BroadcastWith() any {
return map[string]any{"id": e.OrderID, "status": e.Status}
}
func (e OrderUpdated) BroadcastAs() string {
return "order.updated"
}
func (e OrderUpdated) BroadcastWhen() bool {
return e.Notify
}BroadcastWith must return a value that encodes as a JSON object. When BroadcastWhen returns false, or BroadcastOn returns no channels, Laravel skips the broadcast while still running the event's listeners. By default, an event broadcasts under its type's name, such as OrderUpdated. When listening for events in Echo, prefix any custom name containing dots with a leading dot, such as '.order.updated'.
To push updated values to Inertia's live props, give the event a BroadcastProps method, as covered in the Inertia guide. The props travel with the payload, so every subscriber receives them too.
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 routes/channels.go, which bootstrap/app.go passes as Routes.Channels to serve Echo's requests at POST /broadcasting/auth. Each channel pairs a pattern with an authorization callback that receives the request, so the callback may read the signed-in user and the channel's parameters as a handler would.
For example, suppose your application has an Order model and each user has a TeamID field. The following channel definitions allow users to subscribe to their own orders and to their team's presence channel:
package routes
import (
"strconv"
"go.laravel.com/broadcast"
"go.laravel.com/model"
"go.laravel.com/routing"
"go.laravel.com/web"
"app/models"
)
func Channels(channel *routing.Channels) {
channel.Private("orders.{order}", order)
channel.Presence("teams.{team}", team)
}
func order(r *web.Request) (bool, error) {
user := r.User[models.User]()
if user == nil {
return false, nil
}
order, err := model.FromRoute[models.Order](r, "order")
if err != nil {
return false, err
}
return order.UserID == user.ID, nil
}
func team(r *web.Request) (*broadcast.Member, error) {
user := r.User[models.User]()
if user == nil || strconv.FormatInt(user.TeamID, 10) != r.PathValue("team") {
return nil, nil
}
return &broadcast.Member{
ID: strconv.FormatInt(user.ID, 10),
Info: map[string]any{"id": user.ID, "name": user.Name},
}, nil
}A private channel callback returns true to authorize the subscription or false to deny it. A presence channel callback returns a *broadcast.Member with the member data visible to other subscribers on the channel, or nil to deny the subscription. Only include member fields that every subscriber on the channel may see, and take them from the signed-in user, never from the request's input.
Channel patterns omit the private- or presence- prefix, and each {parameter} matches a single dot-separated segment, which the callback reads with r.PathValue or binds to a model with model.FromRoute. Browsers cannot subscribe to any private or presence channel that has not been registered.
If a callback returns an error that would respond with a 401, 403, or 404 (such as from auth.Authenticated(r), auth.Authorize, or a missing model), Laravel rejects the subscription with a 403 rather than redirecting to a login page. Any other error fails the request as it would fail a handler. The browser only learns that it was refused, so Laravel logs the reason along with the channel's name.
New applications include a sample example-channel in routes/channels.go 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:
npm install @laravel/echo-react laravel-echo pusher-jsEcho 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):
VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
VITE_REVERB_HOST="${REVERB_HOST}"
VITE_REVERB_PORT="${REVERB_PORT}"
VITE_REVERB_SCHEME="${REVERB_SCHEME}"Next, configure Echo once at the top of resources/js/app.tsx:
import { configureEcho } from '@laravel/echo-react';
configureEcho({
broadcaster: 'reverb',
namespace: false,
});By default, Echo prefixes event names with App.Events, which Laravel's events do not use. Setting namespace: false disables that prefix so you can listen for events by the exact name they broadcast with, such as '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:
import { useEcho } from '@laravel/echo-react';
export function OrderStatus({ order }) {
useEcho(`orders.${order.id}`, 'OrderShipped', (event) => {
console.log(event.tracking_number);
});
// ...
}The callback receives the event's payload. To listen for multiple events on the same channel, pass an array of event names:
useEcho(`orders.${order.id}`, ['OrderShipped', 'OrderCancelled'], (event) => {
console.log(event.order_id);
});In TypeScript, pass a type parameter to type the event payload:
type OrderShippedPayload = {
order_id: number;
tracking_number: string;
};
useEcho<OrderShippedPayload>(`orders.${order.id}`, 'OrderShipped', (event) => {
console.log(event.tracking_number);
});useEcho also returns helpers to pause listening, resume listening, or leave the channel early:
const { stopListening, listen, leaveChannel } = useEcho(
`orders.${order.id}`,
'OrderShipped',
(event) => {
console.log(event.tracking_number);
},
);
// Stop listening without leaving the channel...
stopListening();
// Start listening again...
listen();
// Leave the channel...
leaveChannel();警告
Even with namespace: false, Echo converts dots inside an event name into backslashes. Prefix any event name that contains dots with a leading dot, such as '.order.updated' 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:
import { useEchoPublic } from '@laravel/echo-react';
useEchoPublic('deploys', 'DeployFinished', (event) => {
console.log(event.environment);
});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 is the Info returned by your channel authorization callback:
import { useEffect, useState } from 'react';
import { useEchoPresence } from '@laravel/echo-react';
export function TeamMembers({ team }) {
const [members, setMembers] = useState([]);
const { channel } = useEchoPresence(`teams.${team.id}`);
useEffect(() => {
channel()
?.here((members) => setMembers(members))
.joining((member) => setMembers((members) => [...members, member]))
.leaving((member) =>
setMembers((members) =>
members.filter((other) => other.id !== member.id),
),
);
}, [channel]);
return members.map((member) => <span key={member.id}>{member.name}</span>);
}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:
import { useEffect } from 'react';
import { useEchoPresence } from '@laravel/echo-react';
export function MessageBox({ team, user }) {
const { channel } = useEchoPresence(`teams.${team.id}`);
useEffect(() => {
channel()?.listenForWhisper('typing', (event) => {
console.log(`${event.name} is typing...`);
});
}, [channel]);
const typing = () => channel()?.whisper('typing', { name: user.name });
return <textarea onChange={typing} />;
}Connection status
To display whether the browser is connected to Reverb, call useConnectionStatus. It returns connected, connecting, reconnecting, disconnected, or failed:
import { useConnectionStatus } from '@laravel/echo-react';
export function ConnectionIndicator() {
const status = useConnectionStatus();
return <div>Connection: {status}</div>;
}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 the context that broadcast.ToOthers returns:
import (
"go.laravel.com/broadcast"
"go.laravel.com/event"
)
err := event.Dispatch(broadcast.ToOthers(r), events.OrderShipped{
OrderID: 42,
TrackingNumber: "TRACK-123",
InternalNote: "Packed by warehouse B",
})ToOthers 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 carries no socket ID, ToOthers does not exclude anyone.
To send the socket ID on every Inertia request, tell Inertia to read it from Echo in resources/js/app.tsx:
import { socketId } from '@inertiajs/react';
import { configureEcho, echo } from '@laravel/echo-react';
configureEcho({
broadcaster: 'reverb',
namespace: false,
});
socketId.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, such as inside a queued job, you may exclude a specific socket directly with broadcast.ExceptSocket(ctx, "123.456").
An event may also choose how its broadcast travels by defining these optional methods:
| Method | Effect |
|---|---|
BroadcastVia() string | Publishes through the named connection in cfg.Broadcasting.Connections. |
BroadcastQueue() (connection, queue string) | Delivers the broadcast through the given queue connection or queue. An empty string keeps the default. |
For example, this event keeps its broadcasts on a queue of their own, so a busy feed doesn't hold up your application's other jobs:
func (OrderShipped) BroadcastQueue() (connection, queue string) {
return "", "broadcasts"
}One-off broadcasts
Some messages don't warrant a dedicated event type, such as progress updates from a long-running export. You may publish directly to a channel by passing the channel, an event name, and a payload to broadcast.Send. For example, a job exporting a report can broadcast its progress using its ExportID:
package jobs
import (
"context"
"fmt"
"go.laravel.com/broadcast"
)
type ExportReport struct {
ExportID int64
}
func (j ExportReport) Handle(ctx context.Context) error {
// Export the first rows...
return broadcast.Send(
ctx,
broadcast.Private(fmt.Sprintf("exports.%d", j.ExportID)),
"export.progress",
map[string]any{"percent": 75},
)
}The payload must encode as a JSON object. Send delivers through the queue as broadcast events do, while SendNow publishes immediately. Both leave out a browser when you pass them the context that ToOthers or ExceptSocket returns. To choose a connection or queue, start with broadcast.Via, broadcast.OnConnection, or broadcast.OnQueue, as in broadcast.OnQueue("exports").Send(...). 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, such as for an invalid REVERB_APP_SECRET, the job fails immediately with Reverb's error message. Inside a database transaction, the broadcast waits until the outermost transaction commits, and a rollback discards it so browsers never receive updates for rolled-back data:
err := db.Transaction(r, func(ctx context.Context) error {
_, err := db.Table("orders").
Where("id", "=", 42).
Update(ctx, db.Values{"status": "shipped"})
if err != nil {
return err
}
return event.Dispatch(ctx, events.OrderShipped{OrderID: 42})
})To publish without using the queue, give the event a BroadcastNow method that returns true. Dispatching then publishes right away and returns any Reverb error directly. Inside a transaction, the broadcast still waits for the commit. If it fails then, the data stays committed, and db.Transaction reports the error as a *db.AfterCommitError rather than returning it:
func (OrderShipped) BroadcastNow() bool {
return true
}Most applications should leave broadcasting on the queue so a Reverb outage doesn't fail incoming requests. Reach for BroadcastNow only when an update must reach browsers without waiting for a queue worker.
Testing
Call broadcasttest.New with your test's client to record broadcasts in memory instead of queueing or publishing them. The event's listeners still run as normal:
package feature_test
import (
"testing"
"go.laravel.com/broadcast"
"go.laravel.com/broadcasttest"
"app/events"
"app/tests"
)
func TestShippingAnOrderBroadcastsIt(t *testing.T) {
client := tests.New(t)
broadcasts := broadcasttest.New(client)
client.Post("/orders/42/ship", nil).AssertNoContent()
broadcasts.AssertBroadcasted(func(_ events.OrderShipped, b broadcasttest.Broadcast) bool {
return b.Channels[0] == broadcast.Private("orders.42") &&
b.Payload()["tracking_number"] == "TRACK-123" &&
b.Payload()["InternalNote"] == nil
})
}The function receives the event and its Broadcast, which holds the channels and payload that subscribers would have received. Payload decodes the payload into a map[string]any (where JSON numbers decode as float64), or call b.JSON[T]() to decode it into a typed struct. The broadcast fake also provides AssertBroadcastedTimes, AssertNotBroadcasted, and AssertNothingBroadcasted, and AssertBroadcasted may be called with only the event's type, as in broadcasts.AssertBroadcasted[events.OrderShipped](). To inspect a one-off broadcast, look it up by event name:
progress := broadcasts.Named("export.progress")
if len(progress) != 1 || progress[0].Payload()["percent"] != 75.0 {
t.Errorf("the export's progress was broadcast as %v", progress)
}An event fake records the event without broadcasting it, so use broadcasttest.New on its own when testing broadcasts. If the test also fakes the queue, install the broadcast fake too, since the queue fake would otherwise hold each broadcast's job without running it.