pexels tima miroshnichenko 5380664

Laravel Reverb: Building Real-Time Applications with WebSockets

·

Real-time functionality – live notifications, collaborative editing, live dashboards, chat – used to mean reaching for a third-party service. Pusher and Ably are both solid, but they add a recurring cost, a dependency on a third-party’s availability, and complexity for environments where you want everything self-hosted. Laravel Reverb changes this by providing a first-party WebSocket server that integrates natively with Laravel Broadcasting.

Understanding the Stack

  • Reverb – the WebSocket server (handles persistent connections)
  • Laravel Broadcasting – the PHP-side abstraction for dispatching events to channels
  • Laravel Echo – the JavaScript client that subscribes to channels
  • Pusher JS – the WebSocket protocol library Echo uses (Reverb implements the Pusher protocol)

Reverb is wire-compatible with existing Laravel Broadcasting code. Switching from Pusher to Reverb often requires only a configuration change.

Installation

php artisan install:broadcasting
# Installs Reverb, Echo, and Pusher JS

# Or manually
composer require laravel/reverb
php artisan reverb:install

npm install --save-dev laravel-echo pusher-js
npm run dev

php artisan reverb:start

Environment Configuration

# .env
REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret
REVERB_HOST=localhost
REVERB_PORT=8080
REVERB_SCHEME=http

Broadcasting Events

php artisan make:event OrderStatusUpdated

// app/Events/OrderStatusUpdated.php
class OrderStatusUpdated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(
        public Order $order,
        public string $status
    ) {}

    public function broadcastOn(): array
    {
        return [
            new PrivateChannel('orders.' . $this->order->id),
        ];
    }

    public function broadcastWith(): array
    {
        return [
            'order_id' => $this->order->id,
            'status' => $this->status,
            'updated_at' => $this->order->updated_at->toISOString(),
        ];
    }

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

// Dispatch
broadcast(new OrderStatusUpdated($order, 'shipped'))->toOthers();

Channel Types

Private Channels

// routes/channels.php
Broadcast::channel('orders.{orderId}', function ($user, $orderId) {
    return $user->orders()->where('id', $orderId)->exists();
});

// JavaScript
Echo.private('orders.' + orderId)
    .listen('.order.status.updated', (e) => {
        updateOrderStatus(e.status);
    });

Presence Channels (Who’s Online)

// routes/channels.php
Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
    if ($user->canJoin($roomId)) {
        return ['id' => $user->id, 'name' => $user->name];
    }
});

// JavaScript
Echo.join('chat.' + roomId)
    .here((users) => setUsers(users))
    .joining((user) => addUser(user))
    .leaving((user) => removeUser(user))
    .listen('.message.sent', (e) => addMessage(e));

Frontend Setup (Echo)

// resources/js/bootstrap.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'],
});

Production Deployment

# Supervisor config
[program:reverb]
command=php /var/www/your-app/artisan reverb:start --host="0.0.0.0" --port=8080
autostart=true
autorestart=true
user=www-data
stdout_logfile=/var/log/reverb.log

# Nginx WebSocket proxy
location /app/ {
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_pass http://127.0.0.1:8080;
}

# Restart after deploy
php artisan reverb:restart

Horizontal Scaling

// config/reverb.php
'servers' => [
    'reverb' => [
        'scaling' => [
            'enabled' => true,
            'channel' => 'reverb',
            'driver' => 'redis',
            'connection' => 'default',
        ],
    ],
],

Conclusion

Reverb removes the Pusher/Ably dependency cleanly. If you’re already using Laravel Broadcasting, the migration is mostly a configuration change. For new projects, it means proper real-time functionality without per-connection pricing. The Pusher protocol compatibility means the Echo and Pusher JS ecosystem continues to work without modification.


Leave a Reply