Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Broadcast Channels - check connections

I can't find this in the docs or by searching, maybe someone has some tips. I'm trying to check how many connections are on a presence channel on the backend.

I can check fine on the front-end with Echo like so:

Echo.join('chat')
    .here((users) => {
        // users.length is the proper count of connections
    })

But is there a way I can get that same number of connections, but in the backend code somewhere within Laravel?

like image 228
Westwick Avatar asked May 19 '17 18:05

Westwick


Video Answer


1 Answers

If you are using Pusher, the backend can just do the following:

$response = $pusher->get( '/channels/presence-channel-name/users' );
if( $response[ 'status'] == 200 ) {
  // convert to associative array for easier consumption
  $users = json_decode( $response[ 'body' ], true )[ 'users' ];
}

$userCount = count($users);

You can read more about it in the pusher documentation. The pusher-http-php sdk also has some documentation for this.

A list of users present on a presence channel can be retrieved by querying the /channels/[channel_name]/users resource where the channel_name is replaced with a valid presence channel name.

This is explicitly only for presence channels.

Additionally, you can keep track of users in channels through webhooks.

Notify your application whenever a user subscribes to or unsubscribes from a Presence channel. For example, this allows you to synchronise channel presence state on your server as well as all your application clients.

Pusher will hit your server with information in the following form:

{
  "name": "member_added", // or "member_removed"
  "channel": "presence-your_channel_name",
  "user_id": "a_user_id"
}

This data could potentially be stored in a table in your database or alternatively in redis.

like image 69
Alex Harris Avatar answered Oct 02 '22 05:10

Alex Harris