Files
chatroom/app/Events/FriendRemoved.php
lkddi 7bae5e56ff 修复:私有频道改用数字 ID,解决中文用户名导致 Pusher 频道名非法
错误原因:Pusher 频道名只允许 [a-zA-Z0-9_\-=@,.],
中文用户名(如「超级舞魅」)用于 private-user.{username} 导致
PusherException: Invalid channel name。

修复方案(改用数字 ID):
- FriendAdded/FriendRemoved 构造加 toUserId 参数
- broadcastOn() 改为 PrivateChannel('user.' . $toUserId)
- FriendController 传入 $target->id / $targetUser->id
- channels.php 鉴权改为 'user.{id}',核对 $user->id 数字相等
- frame.blade.php chatContext 加 userId
- scripts.blade.php Echo.private 改用 userId 订阅
2026-03-01 01:41:04 +08:00

73 lines
2.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 文件功能:好友删除广播事件
*
* 当用户 A 删除用户 B 为好友时,向 B 的私有频道广播此事件。
* 频道名使用数字 IDuser.{id}),避免中文用户名导致 Pusher 频道名验证失败。
*
* @author ChatRoom Laravel
*
* @version 1.0.0
*/
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class FriendRemoved implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* 构造好友删除事件。
*
* @param string $fromUsername 发起删除的用户名A
* @param string $toUsername 被删除的用户名B用于消息显示
* @param int $toUserId 被删除用户的数字 ID用于私有频道避免中文名非法
* @param bool $hadAddedBack B 之前是否也将 A 加为好友(互相好友=true
*/
public function __construct(
public readonly string $fromUsername,
public readonly string $toUsername,
public readonly int $toUserId,
public readonly bool $hadAddedBack = false,
) {}
/**
* 广播到被删除用户的私有频道(用数字 ID 命名,避免中文频道名不合法)。
*/
public function broadcastOn(): Channel
{
return new PrivateChannel('user.'.$this->toUserId);
}
/**
* 指定广播事件名称(短名),供前端 listen('.FriendRemoved') 匹配。
*/
public function broadcastAs(): string
{
return 'FriendRemoved';
}
/**
* 广播负载:包含发起人信息和之前互相好友状态,供前端弹窗使用。
*
* @return array<string, mixed>
*/
public function broadcastWith(): array
{
return [
'from_username' => $this->fromUsername,
'to_username' => $this->toUsername,
'type' => 'friend_removed',
'had_added_back' => $this->hadAddedBack,
];
}
}