Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 67 ยท Queues, Events and Notifications

Real-Time Features with Broadcasting and Reverb

Push live updates to the browser with Laravel broadcasting: broadcast events, public, private and presence channels, authorization, Reverb and Echo.

Normal web pages work by asking: the browser requests, the server answers. But some features need the server to speak first. A chat message should appear on every screen, an order status should change without a refresh, a dashboard counter should tick up. Polling the server every few seconds works but wastes requests and still feels slow. WebSockets keep a connection open so the server can push data the moment something happens.

Laravel's broadcasting feature connects your events to WebSockets. You mark an event as broadcastable, name the channel it goes to, and Laravel sends it to a WebSocket server. Laravel Reverb is the first-party WebSocket server, written in PHP, and Laravel Echo is the JavaScript library that listens in the browser.

Laravel and WebSocket servers cannot run on this site, so all real Laravel and JavaScript code below is read-only. The runnable examples are plain PHP stand-ins that simulate a publish/subscribe hub and channel authorization, and each section says which is which.

The big picture

flowchart LR
    A["Laravel app<br/>event: OrderShipped"] -->|"queued job publishes"| R["Reverb<br/>WebSocket server"]
    R -->|push| B1["Browser 1<br/>Echo"]
    R -->|push| B2["Browser 2<br/>Echo"]
    B1 -.->|"POST /broadcasting/auth<br/>(private channels)"| A

Your app publishes events to the WebSocket server, which pushes them to subscribed browsers. Browsers ask your app for permission to join private channels.

Two directions are involved. Server to browser data travels through Reverb. Permission checks go back to your Laravel app over a normal HTTP request, so the rules stay in your PHP code.

Setting up

In a fresh Laravel app, one command prepares broadcasting:

Terminal
php artisan install:broadcasting

It creates routes/channels.php, the Echo JavaScript setup, and offers to install Reverb. Then start the server:

Terminal
php artisan reverb:start

Reverb speaks the Pusher protocol, which is why the Echo setup uses the pusher-js library underneath. Credentials such as REVERB_APP_ID, REVERB_APP_KEY and REVERB_APP_SECRET go in .env. Hosted services like Pusher Channels and Ably are alternatives with the same event code on your side: you only change the driver (BROADCAST_CONNECTION) and credentials. In production, run Reverb under a process manager next to your queue workers, put TLS in front of it, and read the scaling notes for multiple servers (it can use Redis to share connections).

A broadcast event

An event becomes broadcastable when it implements ShouldBroadcast:

PHP
<?php

namespace App\Events;

use App\Models\Order;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class OrderShipped implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(public Order $order)
    {
    }

    /** @return array<int, Channel> */
    public function broadcastOn(): array
    {
        return [new PrivateChannel("orders.{$this->order->id}")];
    }

    public function broadcastAs(): string
    {
        return 'order.shipped';
    }

    /** @return array<string, mixed> */
    public function broadcastWith(): array
    {
        return [
            'id' => $this->order->id,
            'status' => 'shipped',
        ];
    }
}

Then dispatch it like any event: OrderShipped::dispatch($order).

  • broadcastOn() lists the channels.
  • broadcastAs() sets the event name the browser listens for. Without it, the name is the class name, including its namespace.
  • broadcastWith() chooses the payload. By default Laravel sends all public properties of the event. Send only what the browser may see, since anyone who can join the channel receives it. Never include secrets or whole models with hidden attributes.

ShouldBroadcast events are pushed through the queue, so a queue worker must be running. The class ShouldBroadcastNow sends immediately in the request, which is handy while learning but adds latency to the request. For events raised inside a database transaction, use ShouldDispatchAfterCommit so a client never learns about data that gets rolled back.

Channels and authorization

There are three kinds of channel:

Channel Class Who can join
Public Channel Anyone who knows the name
Private PrivateChannel Users your code authorizes
Presence PresenceChannel Authorized users, plus everyone sees who is present

The names of private channels are prefixed with private- on the wire and presence channels with presence-, but you never type that prefix in PHP or Echo.

Authorization rules live in routes/channels.php:

PHP
use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('orders.{order}', function (User $user, Order $order) {
    return $user->id === $order->user_id;
});

Broadcast::channel('chat.{room}', function (User $user, int $room) {
    if ($user->rooms()->whereKey($room)->exists()) {
        return ['id' => $user->id, 'name' => $user->name];
    }
    return false;
});

When the browser tries to subscribe to a private or presence channel, Echo sends a request to /broadcasting/auth (with the user's session cookie or token). Laravel finds the matching Broadcast::channel rule, runs the callback and answers yes or no. For a presence channel, the returned array is the user's public information that other members see. Route model binding works in channel callbacks, as in routing.

Treat these callbacks like policies: if you forget them, or return true too easily, strangers can read private data in real time.

Listening with Echo

In the browser, Echo subscribes and calls your function when an event arrives. This is read-only JavaScript:

JavaScript
Echo.private(`orders.${orderId}`)
    .listen('.order.shipped', (event) => {
        document.querySelector('#status').textContent = event.status;
    });

Echo.join(`chat.${roomId}`)
    .here((users) => renderMembers(users))
    .joining((user) => addMember(user))
    .leaving((user) => removeMember(user))
    .listen('.message.sent', (event) => appendMessage(event));

Echo.channel('announcements')
    .listen('.maintenance.scheduled', (event) => showBanner(event));

The leading dot in .order.shipped tells Echo that the name is the exact string from broadcastAs() and should not be prefixed with the app's event namespace. Without broadcastAs(), you listen with the class name, for example .listen('OrderShipped', ...), for events in App\Events. Call Echo.leave(...) when the user leaves a page that was listening, so connections do not pile up.

Broadcasting also powers client events (whispers) such as "Ada is typingโ€ฆ", sent directly between clients on private or presence channels without touching your server's PHP code. And the broadcast channel of notifications can push a notification to a user's private channel so a bell icon updates live.

A publish/subscribe hub

A WebSocket server is, at heart, a table of channels and the subscribers listening to each. Publishing means "call every subscriber of this channel". This stand-in has that table, plus authorization callbacks for private channels in the style of routes/channels.php. Subscribers are PHP closures instead of browsers.

PHP A simulated broadcast hub with authorization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Bob is denied on the private channel, so only Ada receives the order update, while the public announcements channel needs no check. In real Laravel the decision happens in the /broadcasting/auth request, and the hub is the Reverb server, but the shape is the same.

Presence: who is here?

A presence channel adds membership. Echo's here, joining and leaving callbacks come from the server tracking who is subscribed. This stand-in tracks members and prints the same three kinds of messages:

PHP A presence channel stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Practical advice

  • Think about load. Every connection holds a socket open. Reverb handles many thousands per process, but plan for connection limits, TLS and scaling when you launch.
  • Do not trust the client. Whatever arrives through a whisper is user input. Persist important data through normal HTTP requests and validation, and use broadcasting to notify about it.
  • Keep payloads small. Send an ID and a few fields and let the browser fetch more if it needs it.
  • Have a fallback. Connections drop; when the page reconnects, fetch the current state from the server instead of relying only on missed events.
  • Test the event, not the socket. Use Event::fake() to assert that the event was dispatched, and unit-test your channel authorization callbacks. See faking and mocking.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes an event broadcast to WebSocket clients?

    An event that implements ShouldBroadcast is pushed to the broadcasting driver, and broadcastOn() returns the channels it goes to.
  2. 2. How does Laravel decide whether a browser may join a private channel?

    Echo asks your app at /broadcasting/auth, and Laravel runs the matching Broadcast::channel callback, which returns true, false or user data for presence channels.
  3. 3. Why is broadcastWith() useful?

    By default all public event properties are sent. broadcastWith() lets you choose a small, safe payload.
  4. 4. What is the difference between a private and a presence channel?

    Both require authorization, but a presence channel also tracks its members and exposes here, joining and leaving events to clients.

Summary

  • Broadcasting pushes events to browsers over WebSockets; Reverb is Laravel's first-party WebSocket server and Echo is the browser library.
  • Make an event implement ShouldBroadcast, return channels from broadcastOn(), name it with broadcastAs(), and limit data with broadcastWith().
  • Channels are public, private or presence; private and presence ones are authorized in routes/channels.php through /broadcasting/auth.
  • Run a queue worker for ShouldBroadcast, and Reverb under a process manager in production.
  • Send small payloads, never trust whispers, and fetch fresh state after reconnecting.

Next: Caching