Skip to content
Laravel Backend Software Architecture

Who Is Online Right Now? Presence in Laravel Without a Heartbeat

Raheel Shan

Raheel Shan

November 28th, 2026 · 7 min read

Who Is Online Right Now? Presence in Laravel Without a Heartbeat

The first version of this article needed a heartbeat, a table, a scheduled command and a sendBeacon route to answer one question: who is in this room?

The hub answers it itself now. Here is what I deleted, and what replaced it.

What I deleted

→ A heartbeat from every browser every 60 seconds (about 17 messages a second at 1,000 users, a sixth of the app limit)
→ The user_presence table → The sweep command and its cron entry
→ The sendBeacon leave route and its CSRF workaround → A 150-second delay before anyone showed as gone

How presence works

Presence belongs to channels. When a user joins a channel, the hub records it. When their last connection in that channel closes, the hub removes them.

→ Counted per user, not per connection. A user with two tabs is one member. The join event fires on their first connection in the channel, and the leave event on their last.
→ Events arrive as ordinary messages. They come from $server, with channel set, and the event name is $presence.join or $presence.leave. The payload is { userId }.
→ Nobody can forge them. $ is not allowed in event names a client can send, so only the hub can produce these.
→ You are not told about yourself. The joiner hears about everyone else, and everyone else hears about the joiner.
→ Disconnects clean up. When a connection drops, the hub removes the user from every channel that connection was in.
→ They do not count as messages. Presence events skip schemas and are not part of your message totals.
→ Flapping is rate-limited. Joining and leaving use the connection's own rate limit, so a client cannot flood a channel with presence events.

The state is in the hub's memory. Your database never holds it.

Two meanings of "online"

Article 6 joins only the room the user has open. So presence there means "looking at this room right now".

For an "online" dot next to every room in a list, the user has to be in all of their channels. A connection can be in 20, so that works for up to 20 rooms. Beyond that, show presence only in the open room.

Pick the meaning before you build the screen. They are different features.

The client

The browser client has a handler for it. Pass onPresence next to onEvent:

const online = new Set();

const client = createRealtimeClient({
    hubUrl: 'https://realtimehub.raheelshan.com/hub/chat',
    fetchToken,
    channels: [`room.${roomId}`],
    onPresence: ({ channel, userId, type }) => {
        if (type === 'join') online.add(String(userId));
        if (type === 'leave') online.delete(String(userId));
        renderOnline(online);
    },
    onEvent: (m) => {
        // ...chat and typing handling from article 6
    },
});

type is join or leave, and it is never about yourself. Presence events go to onPresence and not to onEvent, so your chat handler never sees them. Without the wrapper they arrive in your normal receive handler as $presence.join and $presence.leave from $server.

The starting list

Events only tell you about changes. When a user opens a room they also need the current members. The client gets them from the hub directly: joinChannel returns them, and getPresence asks again later.

const { count, users } = await client.joinChannel(`room.${roomId}`);
const again = await client.getPresence(`room.${roomId}`);   // channels you are in

users.forEach((id) => online.add(String(id)));
renderOnline(online);

The list includes you. The count is exact, and users holds up to 1,000 ids, which are your own user ids, so you turn them into names from your own database. You can only ask about a channel you are in.

A user who connects at the instant you join can be announced even though they are already in your list. Treat each event as adding or removing an id from a set, as the code above does, and the duplicate does no harm.

The backend can use it too

Your server asks the same question with the package:

use Ohad\RealtimeHub\Facades\RealtimeHub;

$presence = RealtimeHub::presence("room.{$room->id}");   // ['channel' => ..., 'count' => 2, 'users' => ['7', '12']]

Outside PHP it is GET /api/channels/{channel}/presence?appKey=... with the app secret as a Bearer token. A bad channel name throws InvalidArgumentException, and a refusal from the hub throws RealtimeHubException.

That settles a question from article 10: send a push notification only to members who are not currently in the channel.

$inRoom = collect($presence['users'])->map(fn ($id) => (int) $id);

$room->members()
    ->whereNotIn('users.id', $inRoom)
    ->each(fn ($user) => $user->notify(new NewRoomMessage($message)));

The check is a point in time, so someone can join a second later. A duplicate push to a person who is already looking is a small cost.

What to watch

→ One server. Presence lives in the memory of one hub instance. With several servers, each lists only its own connections. The hosted hub runs one today.
→ Restarts. A restart empties it. Clients reconnect and rejoin, and the presence events fire again as they do. Expect a short burst of joins after a deploy.
→ No metadata. Presence is a user id and nothing else. Names, avatars and "away" states come from your database.
→ Detection time. A browser that closes cleanly is removed at once. One that loses its network is removed when the hub notices the connection is gone, which takes longer.
→ Big rooms. Every join and leave goes to every member. A room of 5,000 people produces 5,000 events for each person who arrives. Skip presence events in rooms that large.

The rule

Presence is a fact about a connection, so the hub knows it. Your app only needs to turn user ids into names.

Previous: Real-Time Chat Rooms in Laravel: Control Who Joins and Who Posts

Next: Reverb, a Hub or Pusher? How to Pick a Laravel Real-Time Setup

Comment "ONLINE" and I'll send you the presence route and the client snippet as a copy-paste starter.

Found this useful?

Support the work that goes into these posts.

Support
Comments


Comment created and will be displayed once approved.