Laravel

Real-Time Notifications in Laravel with Reverb and Echo

Polling an endpoint every few seconds is the simplest way to show new notifications, but it sends a request from every open tab whether or not anything changed. WebSockets reverse that: the browser keeps one connection open, and the server pushes a message only when there's something to show.

For years the usual self-hosted option in Laravel was beyondcode/laravel-websockets. That package was archived in early 2024 and doesn't support Laravel 11 or later. Its replacement is Laravel Reverb, a first-party WebSocket server that speaks the Pusher protocol, so Laravel Echo and pusher-js work with it unchanged. This guide builds per-user notifications on Reverb, and the last section covers moving an existing laravel-websockets setup across.

How the Pieces Fit Together

  1. Your code dispatches an event that implements ShouldBroadcast.
  2. A queue worker picks it up and sends it to Reverb over HTTP.
  3. Reverb pushes it to every browser subscribed to that event's channel.
  4. Laravel Echo in the browser receives it and calls your listener.

For a private channel, Echo first asks your app (POST /broadcasting/auth) whether the logged-in user may subscribe. Your channel authorization callbacks answer that.

Step 1: Install Broadcasting and Reverb

On Laravel 11 or later, one command sets up everything: it creates routes/channels.php, installs Reverb, writes the .env keys and installs the frontend packages.

Bash
php artisan install:broadcasting

Choose Reverb when prompted. The relevant .env entries look like this:

.env
BROADCAST_CONNECTION=reverb

REVERB_APP_ID=123456
REVERB_APP_KEY=generated-key
REVERB_APP_SECRET=generated-secret
REVERB_HOST=localhost
REVERB_PORT=8080
REVERB_SCHEME=http

VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
VITE_REVERB_HOST="${REVERB_HOST}"
VITE_REVERB_PORT="${REVERB_PORT}"
VITE_REVERB_SCHEME="${REVERB_SCHEME}"

Only variables prefixed with VITE_ reach the browser bundle. The app secret must never be exposed to the frontend.

Step 2: Configure Echo

The installer writes resources/js/echo.js and imports it from resources/js/app.js. It should look roughly like this:

JavaScript
// resources/js/echo.js
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'reverb',
    key: import.meta.env.VITE_REVERB_APP_KEY,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
    wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

Step 3: Create a Broadcast Event

Bash
php artisan make:event OrderShipped
PHP
<?php

namespace App\Events;

use App\Models\Order;
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) {}

    public function broadcastOn(): array
    {
        return [new PrivateChannel('App.Models.User.'.$this->order->user_id)];
    }

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

    // Send only what the UI needs; by default every public property is serialized.
    public function broadcastWith(): array
    {
        return [
            'order_id' => $this->order->id,
            'message' => "Order #{$this->order->id} has shipped.",
        ];
    }
}

Dispatch it wherever the state change happens:

PHP
$order->update(['status' => 'shipped']);

OrderShipped::dispatch($order);

ShouldBroadcast events are queued, so a queue worker has to be running (php artisan queue:work). If you want the broadcast to wait until a surrounding database transaction commits, implement ShouldDispatchAfterCommit as well. Otherwise the browser may receive the event and refetch data that isn't committed yet.

Step 4: Authorize the Private Channel

routes/channels.php decides who may subscribe. The installer already includes this rule for the default user channel:

PHP
use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Without a callback that returns true, the subscription fails with a 403 from /broadcasting/auth. If your frontend is a separate SPA that authenticates with Sanctum, register the broadcasting routes with Sanctum's middleware (Broadcast::routes(['middleware' => ['auth:sanctum']])) and make sure Echo sends the session cookie or token with the auth request.

Step 5: Listen in the Browser

JavaScript
// userId comes from your page or SPA state
window.Echo.private(`App.Models.User.${userId}`)
    .listen('.order.shipped', (event) => {
        showToast(event.message);
    });

Note the leading dot in .order.shipped. When an event uses broadcastAs(), Echo needs the dot to skip prefixing the name with the App\Events namespace. Forgetting it is the most common reason a listener never fires even though Reverb shows the message being sent.

💡 Tip: If you already send database or mail notifications through Laravel's notification system, add 'broadcast' to the notification's via() method instead of writing a separate event. Then listen with Echo.private(...).notification(callback).

Step 6: Run It

During development you need three processes:

Bash
php artisan reverb:start --debug   # WebSocket server, logs connections and messages
php artisan queue:work             # sends queued broadcasts to Reverb
npm run dev                        # Vite

In production, run reverb:start and the queue worker under a process manager such as Supervisor, and put Reverb behind your web server or load balancer so browsers connect over wss:// on port 443. Reverb holds one open connection per browser tab, so raise the process's open-file limit (ulimit -n) if you expect thousands of concurrent users. To run more than one Reverb server, enable horizontal scaling (REVERB_SCALING_ENABLED=true), which coordinates the servers through Redis.

Migrating from beyondcode/laravel-websockets

Because both servers speak the Pusher protocol, the migration mostly touches configuration:

  1. Upgrade to Laravel 11 or later, composer remove beyondcode/laravel-websockets, then run php artisan install:broadcasting and choose Reverb.
  2. Replace the PUSHER_* variables and BROADCAST_DRIVER=pusher with the REVERB_* variables and BROADCAST_CONNECTION=reverb.
  3. Update Echo to broadcaster: 'reverb' and move from MIX_*/process.env variables to VITE_*/import.meta.env if you haven't moved off Laravel Mix yet.
  4. Replace php artisan websockets:serve with php artisan reverb:start in your process manager.
  5. Drop the websockets_statistics_entries table. Reverb doesn't use it. Laravel Pulse can show Reverb connection and message metrics instead.

Your events, routes/channels.php callbacks and Echo listeners don't need to change.

Summary

  • Use Laravel Reverb for self-hosted WebSockets on Laravel 11+. beyondcode/laravel-websockets is archived.
  • Broadcast events go through the queue, so a worker must be running, and ShouldDispatchAfterCommit avoids racing your own transactions.
  • Private channels need an authorization callback in routes/channels.php.
  • Listen for broadcastAs() names with a leading dot in Echo.
Advertisement