代码之家  ›  专栏  ›  技术社区  ›  Gammer

带有Laravel Echo服务器的Laravel Echo专用通道| Redis

  •  8
  • Gammer  · 技术社区  · 6 年前

    脚本: 客户可以将客户介绍给其他客户。 每个引用都需要存储在DB表行中。收到转介的客户应看到事件通知。

    创建新的转介并分派事件:

    $totalRefers = [];
    
    foreach ($array as $to) {
        $refer = new ClientReferral;
        $refer->user_id = $user_id;
        $refer->by = $by;
        $refer->to = $to;
    
        $refer->save();
        array_push($totalRefers, $refer);
    
        ReferralSent::dispatch($refer); // Here is the Event
    }
    
    return response()->json([
        'status' => 'Success',
        'message' => 'Client referred successfully to selected professionals.',
        'data' => $totalRefers
    ], 200);
    

    事件 broadcastOn()

    public function broadcastOn() {
        return new PrivateChannel('referral.' . $this->referral->id);
    }
    

    频道:

    Broadcast::channel('referral.{id}', function ($user, $id) {
        // let's say it's true for the time being
        return true;
    });
    

    请求是一个Ajax POST,因此在success回调中:

    console.log('referral created');
    res.data.forEach(function(entry) {
        // window.custom.userId is the authenticated user ID:
        if (entry.refer_to == window.custom.userId) { 
            window.Echo.private('referral.' + entry.id).listen('ReferralSent', ({data}) => {
                console.log('You have received a new referral');
            });
        }
    });
    

    现在,当前代码的问题是

    接收器如何订阅和侦听动态事件?

    有了这个逻辑,我想得到那个特定的引用和它的数据,以HTML的形式显示在通知托盘中。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Cy Rossignol Albert    6 年前

    问题中显示的事件将广播到 只是。但是,订阅此通道的接收器应该接收 .

    与其为引用实体本身创建通道上下文,不如发布到为引用实体指定的通道 接受转介的人。我猜是的 $referral->to 包含该用户的ID:

    public function broadcastOn()
    {
        return new PrivateChannel('referral.' . $this->referral->to);
    }
    

    根据接收转介的用户的ID更新频道以授权当前用户:

    Broadcast::channel('referral.{refereeId}', function ($user, $refereeId) {
        return $user->id == $refereeId;
    });
    

    window.Echo.private('referral.' + window.custom.userId)
        .listen(e => console.log(e.referral));
    

    因为我们不再监听特定的引用ID,所以我们可以在页面加载期间而不是在AJAX响应回调中初始化Echo订户。

    实时 超出正常请求/响应周期的操作(包括AJAX请求)。在这个问题中,我们要为 每一个 当页面不是在特定请求之后加载时的客户,以便他们可以在其他客户向他们推荐客户机时随时接收通知。

    流程如下所示:

    1. Customer 1和Customer 2都打开了应用程序,在客户端启动Echo。
    2. Laravel将事件发布到Customer 2的频道。
    3. 客户2的浏览器通过Echo接收事件,Echo正在该频道上侦听。