【问题标题】:Laravel Livewire Echo configurationLaravel Livewire Echo 配置
【发布时间】:2021-02-24 23:34:02
【问题描述】:

我已经在我的 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',
    ];
}

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

非常感谢! :)

【问题讨论】:

    标签: laravel events echo pusher laravel-livewire


    【解决方案1】:

    在 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)
    {
        
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用以下特定事件名称配置您的侦听器:

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

      由于您使用 Laravel 通知来触发广播而不是可广播事件,因此触发时的事件名称默认为 Illuminate\\Notifications\\Events\\BroadcastNotificationCreated

      在 Echo 中有两种方法可以监听传入的消息:notificationlisten。它适用于您的 vanilla js 的原因是您使用的是 notification 方法,而 livewire 事件侦听器仅适用于 Echo 的 listen,它需要调用事件的名称。

      如果您使用的是 pusher,您可以在 pusher 调试控制台中看到调用事件的名称。

      还要注意并在命名空间事件前添加一个点,如documentation 中所述。

      【讨论】:

        猜你喜欢
        • 2021-10-10
        • 2021-11-25
        • 1970-01-01
        • 2021-01-24
        • 1970-01-01
        • 2021-11-17
        • 2021-06-23
        • 2020-12-12
        • 2021-05-19
        相关资源
        最近更新 更多