Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : Pusher listen for private channel with unique id

I have a news feed, If user X commented on user Y's post then user Y should get a notification. Now the issue is that user Y dont have to the post id on which user X commented on :

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

The event :

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

The channel :

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

And the listener, This is where my question arises that how can postId will come up here :

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

I want to notify the participator or the owner of the post to be notified when a new comment comes up.

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

like image 611
Gammer Avatar asked Nov 20 '25 08:11

Gammer


1 Answers

You would need to fetch all Post IDs of current user. Then subscribe to each related private channel independently.

This is not really scalable in your case.

You'd probably better have one private channel per user:

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

Then broadcast:

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

Then listen:

window.Echo.channel('users.' + userId).listen('CommentCreated', e => {
    console.log(e.comment);
});
like image 155
eightyfive Avatar answered Nov 21 '25 20:11

eightyfive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!