Episode - https://laracasts.com/series/real-time-games-with-laravel/episodes/5
In this episode we use the Echo presence channel to handle when players join and leave a game.
1<script> 2 //... 3 4 Echo.join(`games.${props.game.id}`) 5 .here((users) => players.value = users) 6 .joining((user) => router.reload({ 7 onSuccess: () => players.value.push(user) 8 })) 9 .leaving((user) => players.value.filter(({id}) => id !== user.id));10 11 onUnmounted(() => {12 Echo.leave(`games.${props.game.id}`);13 });14</script>
The presence channel has a few hooks:
here
fires when the component loads, that’s where we can load all users on this page and store them in a prop.joining
fires each time a user… well joins.leaving
is the opposite ofjoining
.
And of course there are the two methods join
and leave
to use in order to allow the hooks to fire.
Like any other channel, the presence channel needs a route:
1Broadcast::channel('games.{game}', function(User $user, Game $game) {2 //...3 4 return ['id' => $user->id];5});
The thing to note is that it doesn’t return just a boolean like normal channels. It returns an array with the id of the user. This makes total sense as it explains how the user
model is available in the various Echo hooks.