Kyre
Kyre

Reputation: 413

broadcasting laravel event and multiple channels

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

Upvotes: 14

Views: 7534

Answers (2)

Nick Howarth
Nick Howarth

Reputation: 634

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;
}

Upvotes: 0

Riajul
Riajul

Reputation: 1300

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)
    ];
}

Upvotes: 32

Related Questions