Search code examples
laravelpusherlaravel-echolaravel-7pusher-js

Laravel Presence Channel: Store Joining and Leaving Users in database


I have this working:

Echo.join(`chat.${roomId}`)
    .here((users) => {
        //
    })
    .joining((user) => {
        this.users.push(user);
        this.saveStatus(user, 'online');
    })
    .leaving((user) => {
        this.users = this.users.filter(u => u.id != user.id);
        this.saveStatus(user, 'offline');
   });

That shows me an accurate list of the Users that are present. But what I want, is to store also their status in the database with a timestamp.

So I thought about this function:

saveStatus(user, status) {
   axios.post("/logbooks", { user_id: user.id, status: "offline"})
}

And call that function in the joining and leaving state. But that's not accurate: it doesn't store values when just one user is online. And when there are 20 users offline, and one user goes offline > it'll store 19 times this value.

Any tips how to get a more accurate online-offline-log to the database?


Solution

  • If you are using Pusher Channels you can configure presence webhooks for your Channels app. You can activate webhooks in your account dashboard on a per app basis.

    The presence webhook will be triggered for the following events; member_added and member_removed (user joins a presence channel or user leaves a presence channel (goes offline)):

    You can listen for these events on your server and then update the user state depending on what events you are receiving.

    If the user can join multiple rooms (channels) at once (e.g. room1, room2, room3) you may want to track whether the user is online or offline by having a user specific presence channel.

    For example if the user was called 'Joe Bloggs' you would join a channel called joebloggs when first connecting to your Pusher app. (if the user joins this channel they are online, if the user leaves this channel they are offline)