*/ public function broadcastOn(): array { if ($this->shouldBroadcastPrivately()) { $privateChannels = []; foreach ($this->resolveVisibleUserIds() as $userId) { $privateChannels[] = new PrivateChannel('user.'.$userId); } return $privateChannels; } return [ new PresenceChannel('room.'.$this->roomId), ]; } /** * 获取广播时的数据 * * @return array */ public function broadcastWith(): array { return [ 'message' => $this->message, ]; } /** * 判断当前消息是否应仅广播给特定用户。 */ private function shouldBroadcastPrivately(): bool { $toUser = trim((string) ($this->message['to_user'] ?? '')); return $toUser !== '' && $toUser !== '大家'; } /** * 解析本条消息真正可见的用户 ID 列表。 * * @return array */ private function resolveVisibleUserIds(): array { $userIds = []; $fromUser = trim((string) ($this->message['from_user'] ?? '')); if ($fromUser !== '') { $senderId = User::query()->where('username', $fromUser)->value('id'); if ($senderId !== null) { $userIds[] = (int) $senderId; } } $toUser = trim((string) ($this->message['to_user'] ?? '')); if ($toUser !== '' && $toUser !== '大家') { $receiverId = User::query()->where('username', $toUser)->value('id'); if ($receiverId !== null) { $userIds[] = (int) $receiverId; } } return array_values(array_unique($userIds)); } }