Real-Time Chat Rooms in Laravel: Control Who Joins and Who Posts
Raheel Shan
November 27th, 2026 · 9 min read
The hub now has channels, and one line in your token route decides who can join which. Leave that line out and any user can join any room by typing its name.
That is the most important sentence in this article, so here is the rest of it.
Want to see rooms working before you read the code? Open the live demo in two browser tabs and send a message from one to the other.
What a channel is
A channel is a room you name yourself. There is nothing to create: it exists while someone is in it.
→ Names use 1 to 64 characters from A-Z a-z 0-9 _ - ., like room.5 or trips.21
→ One connection can be in up to 20 channels
→ A message to a channel reaches everyone in it, and counts as one message however many people are in it
→ The sender hears their own message, so the client skips its own from → The hub sets from from the token, so a browser cannot send as someone else Two limits shape everything below:
→ Channel messages are not saved. The hub does not store them.
→ Channel messages are not sent to your webhook. Your Laravel app never sees them.
So a channel is a delivery tool and not a way to reach your database. That splits a chat feature into two kinds of message.
Two kinds of message
→ Durable: a chat message that must be saved, validated and shown to people who were offline
→ Ephemeral: a typing indicator, a cursor, a "someone joined" blip, which nobody needs after a few seconds
Ephemeral messages go straight over the channel. Your server is never involved, and that is exactly what article 2's whisper was missing and could not give you.
Durable messages go through Laravel, which saves them and then broadcasts to the channel with one call.
The default is open. Close it.
// routes/web.php
Route::get('/hub-token', function () {
$hub = config('hub');
$channels = auth()->user()->rooms()
->pluck('rooms.id')
->map(fn ($id) => "room.$id")
->all();
return Http::withToken($hub['secret'])
->post($hub['url'].'/api/token', [
'appKey' => $hub['key'],
'userId' => (string) auth()->id(),
'channels' => $channels,
])
->throw()
->json();
})->middleware('auth');
The channels list is the authorization. A user with this token can join those channels and nothing else. An empty list means no channels. A connection that asks for a channel its token does not allow is closed.
A token with no channels key at all puts the app in open mode, where any user can join any channel of your app. For a room list that comes from your database, that is a data leak. Always send the key, even when the list is empty.
A token can list up to 50 channels, and a connection can be in 20. A user in more rooms joins only the one they have open.
Join the room that is open
const client = createRealtimeClient({
hubUrl: 'https://realtimehub.raheelshan.com/hub/chat',
fetchToken: () => fetch('/hub-token').then((r) => r.json()),
onEvent,
onStatus,
});
await client.start();
await client.joinChannel(`room.${roomId}`);
// when the user leaves the room
await client.leaveChannel(`room.${roomId}`);
joinChannel throws with the reason when the name is invalid, the token does not allow it, or the 20-channel limit is hit. Channels joined this way are joined again after a reconnect.
The trap: the token is cached
The client caches the token until 30 seconds before it expires. If a user joins a new room through your app, the cached token does not list it, and joinChannel fails with "This token does not allow that channel."
After a membership change, restart the client so it fetches a fresh token:
await client.stop();
await client.start();
await client.joinChannel(`room.${newRoomId}`);
stop() clears the cache. Short token lifetimes (ttlSeconds, 60 to 86,400) reduce the wait but do not remove it.
Durable messages: save, then broadcast
Route::post('/rooms/{room}/messages', function (Request $request, Room $room) {
Gate::authorize('post', $room);
$data = $request->validate(['text' => 'required|string|max:500']);
$message = $room->messages()->create([
'user_id' => auth()->id(),
'text' => $data['text'],
]);
try {
RealtimeHub::broadcast("room.{$room->id}", 'room.message', [
'id' => $message->id,
'from' => auth()->id(),
'text' => $message->text,
]);
} catch (RealtimeHubException $e) {
report($e); // the message is saved, so clients catch up from history
}
return $message;
})->middleware('auth');
Compare it with the old design:
→ No loop over member ids and no chunks of 50
→ No webhook listener and no signature handling for chat
→ One hub call per message, however big the room
→ The post is a normal Laravel route, so validation, policy and throttling work the way they always do
The Gate::authorize('post', $room) is where "is this user a member" is decided for writes. The token's channels list decides it for reads. Both read the same room_user table.
The message is saved before the broadcast, so a failed broadcast never loses it. The catch logs the failure and the response still succeeds.
Ephemeral messages: straight over the channel
let lastTyping = 0;
input.addEventListener('input', () => {
if (Date.now() - lastTyping < 3000) return;
lastTyping = Date.now();
client.sendToChannel(`room.${roomId}`, 'typing', {});
});
onEvent: (m) => {
if (m.channel !== `room.${roomId}` || m.from === me) return;
if (m.event === 'typing') showTyping(m.from);
if (m.event === 'room.message') render(m.payload);
},
Channel messages are not sent to your webhook, so typing never costs your server a request. The three-second throttle keeps it under the hub's 10 messages per second per connection.
Give typing a JSON Schema with no properties, so nothing else can ride on it.
The receive check is routing, not security
m.channel picks the screen. It decides nothing about who may see the message, because the hub only delivers a channel's messages to connections that joined it, and the token decided who could join.
That is the difference from the version where every user receives everything and filters in JavaScript. Here a user who is not in the room never receives the message.
What to watch
→ Removing someone from a room. The token decides at connect and at join. I found nothing that removes a member from a live connection, so a removed user keeps receiving until their connection drops. For content where that matters, send to individuals with send() and not to the channel.
→ Offline members. A channel message is not held for anyone who is not connected. They load history from your database (article 10).
→ Ordering. The saved row is the source of truth, and id lets a client discard a duplicate. The sender hears their own broadcast, so dedupe on id.
→ Presence. Who is in a channel, and who joins or leaves, is covered in article 7.
When to skip channels
A one-to-one chat needs no channel. Send with client.send(otherId, 'chat', payload) and the hub posts it to your webhook, where the package saves it. Channels earn their place when many people share a conversation.
The rule
The token decides who may listen. Your route decides who may speak. The hub delivers to whoever is in the room.
Previous: SignalR for Laravel: Let the Browser Message Your PHP Directly
Next: Who Is Online Right Now? Presence in Laravel Without a Heartbeat
Comment "ROOMS" and I'll send you the token route, the post route, and the client snippet as a copy-paste starter.
Found this useful?
Support the work that goes into these posts.