首页 > 解决方案 > Laravel Livewire Echo 配置

问题描述

我在我的 Laravel 8 应用程序上设置了一个带有 Pusher 和 Echo 的通知系统。它工作正常,我可以在 VanillaJS 中检索通知事件

window.Echo.private('App.Models.User.' + User.id)
.notification((notification) => {
    if (notification.type === 'App\\Notifications\\JobLiked') {
        let count = document.getElementById('count');
        let number = count.innerHTML;
        number++;
        count.innerHTML = number;
    }
});

但现在我想使用 Livewire 监听器来触发我的功能,然后我设置:

public function getListeners()
{
    return [
        "echo-private:App.Models.User.{$this->authId},NotificationSent" => 'notifyNewJobLiked',
    ];
}

但似乎没有任何效果,我也没有错误消息..你知道可能发生什么吗?

非常感谢 !:)

标签: laraveleventsechopusherlaravel-livewire

解决方案


在 livewire 中获取 Echo 通知的正确方法:

public function getListeners()
    {
        $user_id = auth()->user()->id;

        return [
            "echo-notification:App.Models.User.{$user_id}, notification" => 'gotNotification'
        ];
    }

如您所见,频道类型是通知,而不是私有:

回声通知

另外不要忘记在您的频道路由中记录验证用户的身份,就像您对私人频道所做的一样:

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

我学到的另一件事是,您可以从返回的字段中获取通知通道数据。所以你可以这样做:

public function gotNotification($notification)
{
    
}

推荐阅读