Files
chatroom/app/Events/FriendAdded.php
lkddi 7985a9b0d7 修复:FriendAdded/FriendRemoved 加 broadcastAs() 修复私有频道事件名不匹配
前端 .listen('.FriendAdded') 匹配的是短名 FriendAdded,
但默认广播名是 App\Events\FriendAdded(全类名),导致监听器永远不触发。
加 broadcastAs() 返回短名后两端匹配,弹窗可正常弹出。
2026-03-01 01:13:50 +08:00

76 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 的私有频道广播此事件,
* B 的客户端收到后展示弹窗通知。
* 携带 has_added_back 字段:若 B 已将 A 加为好友则为 true双向好友
* 否则为 false前端提示 B 可以点击回加。
*
* @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\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class FriendAdded implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* 构造好友添加事件。
*
* @param string $fromUsername 发起添加的用户名A
* @param string $toUsername 被添加的用户名B接收通知方
* @param bool $hasAddedBack B 是否已将 A 加为好友(互相添加=true
*/
public function __construct(
public readonly string $fromUsername,
public readonly string $toUsername,
public readonly bool $hasAddedBack = false,
) {}
/**
* 广播到被添加用户的私有频道,仅本人可见。
*/
public function broadcastOn(): Channel
{
return new PrivateChannel('user.'.$this->toUsername);
}
/**
* 指定广播事件名称(短名),供前端 listen('.FriendAdded') 匹配。
*
* 默认广播名为全类名 App\Events\FriendAdded
* 指定短名后前端只需 .listen('.FriendAdded')。
*/
public function broadcastAs(): string
{
return 'FriendAdded';
}
/**
* 广播负载:包含发起人信息和互相好友状态,供前端弹窗使用。
*
* @return array<string, mixed>
*/
public function broadcastWith(): array
{
return [
'from_username' => $this->fromUsername,
'to_username' => $this->toUsername,
'type' => 'friend_added',
'has_added_back' => $this->hasAddedBack,
];
}
}