broadcasting laravel event and multiple channels
Asked Answered
W

2

13

I am new in laravel so I googled a lot for different approaches how to create websocket with redis, socket.io in laravel framework. And finally my websocket works as I expected. However I still have unanswered questions related with websockets. Could you please help me find answer?

class TestEvent implements ShouldBroadcast this class definition expects broadcastOn method that broadcasting channel or channels with data to the listeners. Listener in my case is server.js

redis.subscribe('test-channel', 'test-channel-new');
redis.on('message', function (channel, message) {..

as you can see, I want to subscribe two channels, but with different return values for each channel. And I have no luck find any explanation how it achieved. Have I create new event for each channel separately or there exist some trick using broadcastWith?

Thanks a lot

Wolbrom answered 15/12, 2018 at 22:48 Comment(0)
A
31

It's very easy! just return arrays of Channels in broadcastOn method I just did this: Example:

public function broadcastOn()
{
    return [
        new PrivateChannel('App.Message.' . $this->message->to_user_id),
        new PrivateChannel('App.Message.'. $this->message->to_user_id .'.From.'. $this->message->from_user_id)
    ];
}
Aalesund answered 28/3, 2019 at 13:34 Comment(0)
L
0

Thought I would share a similar use case. I basically loop over a collection of users passed into my event and fire the broadcast.

public function broadcastOn(): array
{
    // Create an array of channels for each user to notify
    $channels = [];

    if ($this->usersToNotify) {
        foreach ($this->usersToNotify as $user) {
            $channels[] = new PrivateChannel('my_channel_'.$user->uuid);
        }
    }

    return $channels;
}
Lubumbashi answered 28/6, 2024 at 10:4 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.