php - 拉维尔 : Pusher listen for private channel with unique id

标签 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);
}

channel :

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

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

From where the postId will come to listen and match the channel is listening .

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

我想通知参与者或帖子的所有者在出现新评论时得到通知。

What will be the way around it ? Any alternate way ?

最佳答案

您需要获取当前用户的所有 Post ID。然后独立订阅每个相关的私有(private) channel 。

这在您的情况下并不是真正可扩展的。

您最好为每位用户设置一个私有(private) channel :

// 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);
});

关于php - 拉维尔 : Pusher listen for private channel with unique id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52414238/

相关文章:

php - laravel如何根据消息设置类

.net - 如何控制触发事件处理程序的顺序?

android - OnRestart 与 OnResume - Android 生命周期问题

php - 表格溢出且与页面不对齐

php - 使用 HTML FORM 和 PhP 更新 mySQL 数据库

php - 如何防止 PHP 中的 SQL 注入(inject)?

php - MySQL - 根据 IN () 返回多行

php - 如何获取 Laravel 5.1 中间件中的路由

Laravel Eloquent 模型在 belongsTo 方法中设置条件

c# - 如何在 Sharepoint itemadded 事件中检索查询字符串