Laravel - Broadcasting - Broadcasting To Presence Channels

Presence channels may receive events just like public or private channels. Using the example of a chatroom, we may want to broadcast NewMessage events to the room's presence channel. To do so, we'll return an instance of PresenceChannel from the event's broadcastOn method:

    
    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PresenceChannel('room.'.$this->message->room_id);
    }
	

As with other events, you may use the broadcast helper and the toOthers method to exclude the current user from receiving the broadcast:

    
    broadcast(new NewMessage($message));
    
    broadcast(new NewMessage($message))->toOthers();
	

As typical of other types of events, you may listen for events sent to presence channels using Echo's listen method:

    
    Echo.join(`chat.${roomId}`)
        .here(...)
        .joining(...)
        .leaving(...)
        .listen('NewMessage', (e) => {
            //
        });