Laravel 8 廣播到 Presence 頻道

2021-07-17 17:37 更新

Presence 頻道可以像公共或私私有頻道一樣接收事件。 使用聊天室的示例,我們可能希望將 NewMessage 事件廣播到房間的 Presence 頻道。 為此,我們將從事件的 broadcastOn 方法返回一個 PresenceChannel 實例:

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

與公共或私有事件一樣,可以使用 broadcast 功能來廣播 Presence 頻道事件。 與其他事件一樣,你可以使用 toOthers 方法排除當(dāng)前用戶接收廣播:

broadcast(new NewMessage($message));

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

你可以通過 Echo 的 listen 方法監(jiān)聽 join 事件:

Echo.join(`chat.${roomId}`)
    .here(...)
    .joining(...)
    .leaving(...)
    .listen('NewMessage', (e) => {
        //
    }); 
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號