Laravel Broadcasting: Real-time Events
Someone updates an order in the admin panel, and the customer staring at the order page sees nothing until they hit refresh. So you add a setInterval that polls /api/orders/42 every five seconds. It works, until you have a few hundred people with that tab open and your logs are full of requests that return the exact same JSON. What you actually want is for the server to push the change when it happens.
That's what Laravel Broadcasting does. You fire a normal Laravel event that implements ShouldBroadcast, a queue worker hands it to a WebSocket server (Reverb, Pusher, or similar), and Laravel Echo in the browser runs your callback. This post walks through picking a driver, setting up Reverb, writing broadcastable events, authorizing private and presence channels, wiring up Echo, and the production bits (Supervisor and Nginx) that tend to trip people up.
Polling asks "anything new?" every N seconds, even when the answer is almost always no. With broadcasting, each browser holds one open connection and the update shows up as soon as the server sends it, usually well under a second. If you need near-instant updates or events targeted at specific users, broadcasting is the better fit. For a stats page that refreshes once a minute, polling is honestly fine.
How Laravel Broadcasting Works
It's worth knowing the data flow before you write code, because when something doesn't arrive in the browser you'll need to figure out which piece dropped it. There are five moving parts:
- Event class: A standard Laravel event that implements
ShouldBroadcast(orShouldBroadcastNowfor immediate dispatch) - Queue worker: Picks up the broadcast job and forwards it to the driver
- Broadcasting driver: Pusher, Ably, Laravel Reverb, or Redis. This is the WebSocket server that manages persistent connections
- Laravel Echo: A JavaScript library that subscribes to channels and maps incoming payloads to callbacks
- Channel authorization: Server-side callbacks in
routes/channels.phpthat control which users can subscribe to private or presence channels
Laravel Broadcasting data flow, from firing the event to the browser callback
Choosing a Broadcasting Driver
The driver decides what you pay, what you have to host, and how much ops work lands on you:
| Driver | Hosting | Best For | Cost |
|---|---|---|---|
| Laravel Reverb | Self-hosted (PHP) | Full control, no third-party dependency | Free (server costs only) |
| Pusher | Managed cloud | Fast setup, generous free tier | Free up to 200k daily messages |
| Ably | Managed cloud | Global edge network, high throughput | Free up to 6M messages/month |
| Redis + Socket.io | Self-hosted | Custom Node.js server setups | Free (infrastructure costs) |
For a new project I'd start with Laravel Reverb. It's the first-party WebSocket server, written in PHP, and it runs next to your app. No third-party account, no message quotas, no extra hop to someone else's edge. The catch is that you now own a long-running process that has to stay up. If you don't want that, Pusher is still the easiest way to get going with zero ops. Free tier limits change from time to time, so check the current pricing pages before you rely on the numbers in that table.
Installation and Configuration
Installing Laravel Reverb
Install Reverb via Artisan
Run the install:broadcasting command. It installs the Reverb server, publishes its config, and wires up the Echo scaffolding automatically.
# Install Reverb (first-party WebSocket server)
php artisan install:broadcasting
# This installs reverb, publishes config/reverb.php,
# and sets BROADCAST_CONNECTION=reverb in .env
# Install frontend dependencies
npm install --save-dev laravel-echo
npm install --save pusher-js # Reverb uses Pusher protocol
# Start Reverb server (separate terminal)
php artisan reverb:start
# Start queue worker (events are queued by default)
php artisan queue:work
Configure .env
Set your broadcasting connection and Reverb credentials. The installer fills in most of these, but double check them, especially host and port.
BROADCAST_CONNECTION=reverb
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
VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
VITE_REVERB_HOST="${REVERB_HOST}"
VITE_REVERB_PORT="${REVERB_PORT}"
VITE_REVERB_SCHEME="${REVERB_SCHEME}"
Enable the BroadcastServiceProvider
Uncomment App\Providers\BroadcastServiceProvider::class in config/app.php if it isn't already enabled (older Laravel versions).
Broadcastable events go through Laravel's queue by default. Set QUEUE_CONNECTION to database, redis, or another real driver. With sync, every broadcast runs inside the request and slows it down. And with a real driver but no worker running, nothing reaches the browser at all, with no error anywhere. That second one catches a lot of people. Also remember that a worker keeps your old code in memory, so run php artisan queue:restart after you change an event class.
Using Pusher Instead
If you'd rather use a managed service, switching to Pusher is mostly a package and some env vars:
# Install Pusher PHP SDK
composer require pusher/pusher-php-server
# .env settings
BROADCAST_CONNECTION=pusher
PUSHER_APP_ID=your-app-id
PUSHER_APP_KEY=your-app-key
PUSHER_APP_SECRET=your-app-secret
PUSHER_APP_CLUSTER=mt1
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
Creating Broadcastable Events
Take any event class, add implements ShouldBroadcast, and you're most of the way there. The only required method is broadcastOn(), which returns the channels to send to. There's also ShouldBroadcastNow, which skips the queue and broadcasts during the request. I only reach for it when there's no worker available (some tests, small internal tools), because it makes the HTTP response wait on the WebSocket server.
php artisan make:event OrderStatusUpdated
<?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 OrderStatusUpdated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(public Order $order)
{
//
}
/**
* Channels this event should broadcast on.
* PrivateChannel requires the subscriber to be authorized.
*/
public function broadcastOn(): array
{
return [
new PrivateChannel('orders.' . $this->order->id),
];
}
/**
* Override the event name seen by the frontend.
* Default would be "App\\Events\\OrderStatusUpdated".
*/
public function broadcastAs(): string
{
return 'order.updated';
}
/**
* Customize the payload sent to the frontend.
* By default, all public properties are included.
*/
public function broadcastWith(): array
{
return [
'id' => $this->order->id,
'status' => $this->order->status,
'total' => $this->order->total,
];
}
/**
* Conditional broadcasting: only fire when the status actually changed.
*/
public function broadcastWhen(): bool
{
return $this->order->wasChanged('status');
}
}
You fire it the same way as any other event:
public function updateStatus(Request $request, Order $order): JsonResponse
{
$order->update(['status' => $request->status]);
// This queues the broadcast, so the request doesn't wait
OrderStatusUpdated::dispatch($order);
return response()->json(['message' => 'Status updated']);
}
Channel Types and Authorization
There are three channel types. Pick the wrong one and you either leak data to people who shouldn't see it or miss out on features like "who's online".
Public Channels
Anyone can subscribe, no login needed. Only put data here that you'd be fine posting on your homepage: sports scores, site-wide announcements, a public chat room.
public function broadcastOn(): array
{
return [
new Channel('announcements'),
];
}
Private Channels
Before the WebSocket server lets a browser into a private channel, Echo sends a request to your app's /broadcasting/auth endpoint and your app decides. This is where rules like "only the order owner can listen to order updates" go.
The callbacks live in routes/channels.php. Return true to allow, false to deny:
<?php
use App\Models\Order;
use Illuminate\Support\Facades\Broadcast;
// Private channel: user can only subscribe to their own orders
Broadcast::channel('orders.{orderId}', function ($user, $orderId) {
$order = Order::find($orderId);
return $order && $order->user_id === $user->id;
});
// Private channel: only admins can subscribe
Broadcast::channel('admin.dashboard', function ($user) {
return $user->hasRole('admin');
});
// Using a Gate policy for cleaner authorization
Broadcast::channel('orders.{order}', function ($user, Order $order) {
return $user->can('view', $order);
});
If private channels silently never receive anything, open the browser's network tab and look for POST /broadcasting/auth. A 403 there means either the request wasn't authenticated (no session cookie, common when the frontend lives on a different domain or you use token auth without configuring the auth endpoint) or your callback returned false. Also check the channel name: Laravel adds the private- prefix itself, so it's 'orders.{orderId}' in channels.php and Echo.private('orders.42') in JavaScript, never private-orders by hand.
Presence Channels
A presence channel is a private channel that also knows who's in it. When someone joins or leaves, everyone else subscribed hears about it. That's what you build "who's online" lists, collaborative editors, and "X is typing" indicators on.
// Return user data (not just true/false) for presence channels
Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
if ($user->canJoinRoom($roomId)) {
// Returned array is shared with all members in the channel
return [
'id' => $user->id,
'name' => $user->name,
'avatar' => $user->avatar_url,
];
}
});
// Presence event
class UserJoinedRoom implements ShouldBroadcast
{
public function broadcastOn(): array
{
return [
new PresenceChannel('chat.' . $this->roomId),
];
}
}
Frontend Integration with Laravel Echo
On the browser side, Echo wraps the Pusher JS client (Reverb speaks the same protocol) and gives you channel(), private() and join() to subscribe. Set it up once in resources/js/bootstrap.js or 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'],
});
Listening to Events
// Public channel: no auth required
Echo.channel('announcements')
.listen('AnnouncementPublished', (e) => {
console.log('New announcement:', e.title);
showToast(e.title, e.message);
});
// Private channel: server authorizes via routes/channels.php
// broadcastAs() name used here with leading dot
Echo.private(`orders.${orderId}`)
.listen('.order.updated', (e) => {
document.getElementById('order-status').textContent = e.status;
updateProgressBar(e.status);
});
// Presence channel: membership events included
Echo.join(`chat.${roomId}`)
.here((members) => {
// Called immediately with current member list
updateOnlineList(members);
})
.joining((member) => {
// Called when a new user joins
addToOnlineList(member);
showSystemMessage(`${member.name} joined`);
})
.leaving((member) => {
// Called when a user disconnects
removeFromOnlineList(member.id);
})
.listen('MessageSent', (e) => {
appendMessage(e.user, e.message);
})
.whisper('typing', { name: currentUser.name }); // client-only events
Real-Time Notifications
Notifications can broadcast too. Add 'broadcast' to via(), implement toBroadcast(), and Echo can listen on the user's own private channel without you defining a new event:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;
class InvoicePaid extends Notification
{
use Queueable;
public function __construct(private readonly float $amount) {}
public function via($notifiable): array
{
// Send both email and real-time broadcast
return ['mail', 'broadcast'];
}
public function toBroadcast($notifiable): BroadcastMessage
{
return new BroadcastMessage([
'amount' => $this->amount,
'message' => "Your invoice of \${$this->amount} has been paid.",
]);
}
}
// Laravel maps this to the authenticated user's private channel automatically
Echo.private(`App.Models.User.${userId}`)
.notification((notification) => {
if (notification.type === 'App\\Notifications\\InvoicePaid') {
showNotificationBadge(notification.message);
}
});
Production Deployment
In production, Reverb is a long-running process like your queue worker. Run it under Supervisor so it comes back after a crash or reboot, and put Nginx in front for TLS:
[program:reverb]
command=php /var/www/myapp/artisan reverb:start --host=0.0.0.0 --port=8080
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/log/supervisor/reverb.log
server {
listen 443 ssl;
server_name myapp.com;
# Proxy WebSocket connections to Reverb
location /app/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_read_timeout 60s;
}
}
When I'd use broadcasting (and when I wouldn't)
Before you ship it
- Treat the browser as untrusted: anything in
broadcastWith()ends up in the client. Send IDs and status, not whole models with fields the user shouldn't see. - Don't make broadcasts the source of truth: WebSocket connections drop (laptops sleep, phones switch networks) and missed events are not replayed. Reload the current state from your API when the page loads or reconnects.
- Watch the event name: with
broadcastAs()you listen for'.order.updated'with the leading dot. Without the dot, Echo prefixes your app's event namespace and the listener never fires. - Monitor two processes, not one: Reverb and the queue worker both need Supervisor (or similar) and alerts when they die.
I'd use broadcasting when a user is actively looking at a page and something they care about changes because of someone else: chat, order or job status, live dashboards, collaborative editing. That's where it's clearly better than polling.
I wouldn't bother when updates are rare or nobody needs them instantly. A report that refreshes every few minutes, or a page people visit once a day, is simpler with plain polling or a page reload, and you skip running and monitoring an extra server. It's also the wrong tool for guaranteed delivery. If a message must reach the user, store it (in the database, a notification, an email) and use the broadcast only as a "something changed, go fetch it" signal.