Skip to Content
Course content

217: Presence Channels and Online User Tracking

Click on the "Edit" button in the top corner of the screen to edit your slide content.

We've already covered how to send a private message to a specific user, but that's a one-way street. In a real-world app—like a collaborative document editor or a support dashboard—you often need to know who is currently looking at the same thing as you. That's where Presence Channels come in.

I'm going to show you how to build a "Who's Viewing This Ticket" indicator for a support system. The goal is simple: when an agent or a customer opens a support ticket, everyone else viewing that same ticket sees their name pop up in a list in real-time.

Authorizing the Presence Channel

Unlike private channels, which just return a boolean (true or false) to allow access, presence channels need to return an array of data. This data is what gets broadcast to everyone else when a user joins. If you return false, they're blocked; if you return an array, they're "present."

// routes/channels.php

Broadcast::channel('ticket.{ticketId}', function ($user, $ticketId) {
    // Check if the user is actually assigned to this ticket or is the owner
    if ($user->canViewTicket($ticketId)) {
        return [
            'id' => $user->id, 
            'name' => $user->name, 
            'avatar' => $user->avatar_url
        ];
    }
});

I'm returning the avatar_url here because it's much nicer to show a small circle with a face than just a text string. Keep this array lean, though. Don't dump the whole User model in here; remember, this data is sent to every single client on the channel.

Wiring up the Frontend Listeners

Now we need the JavaScript side to handle three specific events: here (who is already there), joining (someone just arrived), and leaving (someone closed the tab). I usually set up a simple array in my JS state to keep track of these users.

Echo.join(`ticket.${ticketId}`)
    .here((users) => {
        // This fires immediately upon joining
        this.onlineUsers = users;
        this.renderUserList();
    })
    .joining((user) => {
        this.onlineUsers.push(user);
        this.renderUserList();
    })
    .leaving((user) => {
        this.onlineUsers = this.onlineUsers.filter(u => u.id !== user.id);
        this.renderUserList();
    });

The "Why is my list empty?" Moment

I'll be honest: the first time I implemented this in a production project, I spent an hour scratching my head because the here event was never firing. I checked my network tab, and the connection was successful (101 Switching Protocols), but my list stayed empty.

The mistake? I had used Echo.private() instead of Echo.join(). It's a tiny semantic difference in the code, but a huge difference in the backend. A private channel is for security; a presence channel is for membership. Because I used .private(), the server didn't treat the connection as a "presence" event, and it never sent back the list of active users.

If you see your connection working but your here callback isn't triggering, double-check that you're using .join() on the frontend and that your channels.php is returning an array, not just true.

Handling the "Ghost" User

One thing to keep in mind is that presence channels rely on the WebSocket connection staying open. If a user's internet blips or their browser crashes, there's a slight delay before the server realizes they're gone and triggers the leaving event. I've found it's best to avoid using this for mission-critical "locking" (like preventing two people from editing the same field at the exact same millisecond) and instead use it as a visual cue. For hard locks, you'll still want a database-backed lock or a Redis key with a TTL.




📋 Practical Task

Exercise: Implementing a "Live Team" Status Bar

You are building a team dashboard. Your task is to implement a presence channel called team.{teamId}.

  • Backend: Modify the channel authorization logic to ensure that only users who belong to the specified teamId can join. Instead of just returning the user's name, return an array containing their name and their role (e.g., 'Admin', 'Editor', 'Viewer').
  • Frontend: Write the Echo .join() logic to maintain a list of online team members. When a user joins or leaves, the list should update.
  • Challenge: Add a condition in the joining listener that triggers a browser notification or a console log only if the user joining has the 'Admin' role.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.