You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Pusher广播离开房间通知显示错误用户名问题排查

问题原因

  • leaving事件回调逻辑错误:Laravel Echo的leaving事件会自动将离开房间的用户对象作为参数返回,你在调用sendUserActivityNotification时错误传入了当前登录用户this.$page.props.user,导致所有离开通知都显示当前查看页面的用户名。
  • 额外遗漏:joining事件回调仅更新了本地在线用户列表,没有调用通知方法,除当前用户外其他用户进入房间时不会触发提示。

修正代码

你只需要调整connect方法中joining、leaving回调的逻辑即可:

methods: {
    connect() {
        if (this.currentRoom?.id) {
            let vm = this;
            this.getMessages();
            Echo.join("chat." + this.currentRoom.id)
                .here(users => {
                    // 这里是当前用户自己加入房间,传当前用户信息逻辑正确
                    this.sendUserActivityNotification(this.$page.props.user, true)
                    this.users = users
                    this.usersCount = users.length
                })
                .joining(user => {
                    this.users.push(user)
                    this.usersCount = this.usersCount+1
                    // 新增:传入实际加入的用户对象触发通知
                    this.sendUserActivityNotification(user, true)
                })
                .leaving(user => { 
                    // 修正:传入实际离开的用户对象,而非当前登录用户
                    this.sendUserActivityNotification(user, false)
                    this.users = this.users.filter(({id}) => (id !== user.id))
                    this.usersCount = this.usersCount-1
                })
                .listen('NewChatMessage', (e) => {
                    vm.getMessages();
                });
        }
    },
    // 其余方法保持不变即可
    setRoom(room) {
        this.currentRoom = room;
    },
    getMessages() {
        axios.get('/chat/room/' + this.currentRoom.id + '/messages')
            .then(response => {
                this.messages = response.data;
            })
            .catch(error => {
                console.log(error);
            })
    },
    sendUserActivityNotification(user, joining) {
        const message = `${user.name} has ${joining === true ? 'entered' : 'left'} the room.`
        return axios.post(`/chat/room/${this.currentRoom.id}/notifications`, {message}).then(() => this.getMessages())
        .catch(console.error)
    },
    leaveRoom({id}) {
        this.$store.dispatch(RoomTypes.LEAVE_ROOM, id)
    }
},

内容的提问来源于stack exchange,提问作者ArcticMediaRyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 04:18:04