Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mathewparet's avatar

Execute code only if user is actively subscribed to channel (Websockets)

I am aworking on a project where the page needs to be "live". I achieve this using websockets.

Now when a user "clicks" on a model, I want it to be broadcasted. There are two events I call - Clicked, and ChartUpdated.

Clicked receives only the new new click count. I am already receiving it as expected and I show it to the user on the page if the user is on the page that shows the click count.

Now I want to invoke the ChartUpdated event which prepares some chart data (basically last few days of click count and sends it via websocket).

Now I want this part of the code to run only if the user is listening actively the corresponding channel.

How can I achieve this?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To ensure that your ChartUpdated event is only broadcasted to users who are actively subscribed to a specific channel, you can leverage the presence channels feature in Laravel Echo. Presence channels allow you to determine which users are currently subscribed to a channel, and you can use this information to conditionally execute your code.

Here's a step-by-step solution:

  1. Set Up Presence Channel:

    First, ensure that your channel is set up as a presence channel in your routes/channels.php file. This will allow you to track which users are currently subscribed.

    use Illuminate\Support\Facades\Broadcast;
    
    Broadcast::channel('chart-updates', function ($user) {
        return $user; // Return user data to identify them in the presence channel
    });
    
  2. Broadcast the ChartUpdated Event:

    When you want to broadcast the ChartUpdated event, you can check if there are any active subscribers to the channel. This can be done by using the PresenceChannel class to get the list of subscribed users.

    use Illuminate\Support\Facades\Broadcast;
    use App\Events\ChartUpdated;
    
    public function updateChart()
    {
        // Get the list of users subscribed to the 'chart-updates' channel
        $subscribedUsers = Broadcast::channel('chart-updates')->getSubscribedUsers();
    
        // Check if there are any active subscribers
        if (count($subscribedUsers) > 0) {
            // Prepare your chart data
            $chartData = $this->prepareChartData();
    
            // Broadcast the ChartUpdated event
            event(new ChartUpdated($chartData));
        }
    }
    
  3. Listen for the Event on the Frontend:

    On the client side, ensure that you are listening to the ChartUpdated event using Laravel Echo. This will ensure that only users who are actively subscribed to the channel will receive the event.

    import Echo from 'laravel-echo';
    
    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: 'your-pusher-key',
        cluster: 'your-pusher-cluster',
        encrypted: true
    });
    
    Echo.join('chart-updates')
        .listen('ChartUpdated', (e) => {
            console.log('Chart data updated:', e.chartData);
            // Update your chart with the new data
        });
    

By using presence channels, you can effectively determine if there are any active subscribers and conditionally broadcast the ChartUpdated event only when necessary. This approach ensures that your server resources are used efficiently and that only interested users receive the updates.

Please or to participate in this conversation.