Playing
16. Joining and leaving events

Transcript

00:00
OK, so there are two other events that we can listen to on a presence channel. That is joining and leaving.
00:06
So here will always be invoked when the user hits this page and this event gets sent and it will tell us who's currently in the room. But we want to know who joins and who leaves so we can keep this list up to date. Let's go ahead and add in the joining event in here.
00:22
That will just give us a single user who is currently joined. So let's create out a closure for this and let's just console log out that user for now. If we head back over to the browser, let's have a look here.
00:35
I'm going to refresh both of these. You can see Mabel has joined and we'll have exactly the same thing over this side as well. So when Alex joins, you can see that we get this dumped out.
00:45
So this will keep everything up to date for all users. OK, so there's a couple of caveats around this depending on how you're working, but we're just going to say users here and we're just going to push that user to the list. You'll probably want an if statement up
01:00
here to check if they're already in the list and not push to this array. Now, the next event is when a user is leaving. So in this case, we just want to filter out any users who have left. And that will nicely keep the list up to date for us.
01:16
In JavaScript, it looks like this. We're going to go ahead and reassign this to a filtered version. So let's grab users here. We'll filter this for each of these users.
01:26
We just want a condition. So that is that the user ID doesn't equal the user ID who has just joined so that when a user leaves, that will just get rid of them from the list.
01:38
OK, let's go over and see this working. So I'm going to give both of these pages a refresh. I'm going to go back to my dashboard and you can see Mabel has been removed. That's, of course, the leaving event.
01:49
When I go back over to this room, we get a joining event, which has pushed Mabel back to this list. And we can just keep doing that over and over again, and everything is nicely kept up to date.
18 episodes1 hr 19 mins

Overview

New to realtime broadcasting in Laravel? This course covers the essentials with plenty of examples along the way, leaving you ready to start adding realtime functionality to any of your Laravel applications.

Broken up into channel types, we’ll cover:

  • The basics of installing, configuring and running a Reverb server
  • Broadcasting events
  • Private channels
  • Presence channels
  • Client-to-client broadcasting by whispering
Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Episode discussion

No comments, yet. Be the first!