【问题标题】:Laravel broadcast notification to all friendsLaravel 向所有朋友广播通知
【发布时间】:2018-07-13 13:35:32
【问题描述】:

我正在尝试在我的网站上实现通知功能。这是我的代码(希望我的方法是正确的)

-创建一个名为 notification.{userId} 的频道(userId 是经过身份验证的用户 ID) - 例如,当我对他的帖子发表评论时,触发在 notifications 上广播的 NewComment 事件。{$notification->user_id}

这是我的代码:

public function newComment($post, $user){
    $notification = new Notification; // this is notification model for my database table
    $notification->type = 'new-comment';
    $notification->notified_by = $user->id;
    $notification->user_id = $post->owner->id;
    $notification->save();

    event(new NewNotification($notification));
}

NewNotification.php 事件

<?php

namespace App\Events;

use App\Models\Notification;
use App\Transformers\NotificationTransformer;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewNotification
{
    protected $notification;

    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Notification $notification)
    {
        $this->notification = $notification;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PresenceChannel('notification.' . $this->notification->user_id);
    }

    public function broadcastWith(){
        return fractal()->item($this->notification, new NotificationTransformer());
    }
}

广播频道路线:

Broadcast::channel('notification.{userId}', function($user, $userId){
      //comparing ($userId == $user->id) always turns true 
});

在客户端订阅在线状态频道(使用 Vue)

Echo.join('notification.' + this.user_id) //user_id is logged in user id
              .listen('NewNotification', function(response){
                console.log(response);
              });

由于某种原因,事件永远不会被调用。我不知道我是否应该更改广播频道路由中的逻辑。我是否应该传递通知 id 并检查 notification->user_id === $user->id 。我已经测试过这种方式,但在控制台中仍然没有响应。

【问题讨论】:

  • 你的队列驱动设置是什么?
  • @btl,它是数据库。我想我忘了在终端运行队列工作者。我也不确定,如果我使用私人频道,如果频道被占用(只有 1 个用户),是否会在频道中触发事件,因为用户只会收听他的频道?
  • 是的,确保工作人员正在运行。我认为用户需要积极倾听事件路由,但不是 100% 确定。你在用laravel echo server吗?还是只是一个 websocket 本身?
  • 我正在使用 laravel echo 服务器
  • 酷,很高兴它正在工作。您应该设置 supervisor 或 pm2 并让它们在启动时运行。我也忘记了启动队列,所以自动处理它很好。

标签: laravel vuejs2 pusher laravel-echo


【解决方案1】:

我希望有人觉得这个答案有帮助:

为了触发一个事件,事件类应该实现 ShouldBroadcast 类。

所以

class NewNotification{
   //code here
}

变成

class NewNotification implements ShouldBroadcast{
   // code here
}

不要忘记运行队列:如果你还没有设置自动作业,请听

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多