Laravel:Pusher监听具有唯一ID的私人频道

时间:2018-09-19 21:08:31

标签: php laravel events laravel-5 pusher

我有一个新闻提要,如果用户X在用户Y的帖子中发表了评论,那么用户Y应该会收到通知。 现在的问题是用户Y不必输入用户X对其发表评论的帖子ID:

// Create comment 
$comment = new Comment;
$comment->post_id = $post_id;
$comment->user_id = $user_id;
$comment->body = $body;
$comment->save();

// Save activity in database
$newUser = PostActivity::firstOrCreate([
    'post_id'   => $post_id,
],[
    'user_id' => Auth::user()->id,
    'post_id' => $post_id,
    'seen'    => '0'
]);

// Dispatch event with newly created comment

FeedCommentActivity::dispatch($comment);

事件:

public function broadcastOn()
{
    return new PrivateChannel('post-comment-activity.' .$this->activity->post_id);
}

频道:

Broadcast::channel('post-comment-activity.{postId}', function ($user, $postId) {
    // Lets say true for the time
    return true;
});

还有听众,这是我的问题,postId怎么会出现在这里:

  

postId将从哪里收听并匹配该频道,   听。

window.Echo.channel('post-comment-activity' + postId)
        .listen('FeedCommentActivity', e => {
    console.log('New comment by a user');
    console.log(e);
});

我想在出现新评论时通知参与者或帖子的所有者,并通知他们。

  

将如何处理?还有其他方法吗?

1 个答案:

答案 0 :(得分:0)

您需要获取当前用户的所有Post ID。然后独立订阅每个相关的私人频道。

根据您的情况,这并不是真正可扩展的。

您最好为每个用户设置一个私人频道:

// routes/channels.php
Broadcast::channel('users.{user}', function ($currentUser, User $user) {
    return $currentUser->id === $user->id;
});

然后广播:

// app/Events/CommentCreated.php
class CommentCreated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $comment;

    public function __construct(Comment $comment)
    {
        $this->comment = $comment;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('users.' .$this->comment->post->user_id);
    }
    // ...

// app/Observers/CommentObserver.php
class CommentObserver
{
    public function created(Comment $comment)
    {
        broadcast(new CommentCreated($comment))->toOthers();
    }
    //...

然后听:

window.Echo.channel('users.' + userId).listen('CommentCreated', e => {
    console.log(e.comment);
});