Search code examples
laravelbroadcastchannelpusher

Laravel broadcasting a Presence Channel using pusher unable to pass parameters


I've followed the documentation at https://laravel.com/docs/6.x/broadcasting step by step and make sure I copy and paste to be certain I don't make any mistake. I'm able to broadcast just fine and everything is working just fine. Because I'm unable to pass attributes, people in different roomId are counted as if they are all in the same room. Here is the live example: https://prayershub.com/worship/82 - 82 is the worship_id I would like to pass to:

Broadcast::channel('worship_presence_channel.{id}', function ($id) {
if(Auth()->check())
{
    $profile = Auth()->user()->Profile;

    $user = Auth()->user();

    $data = [
        'id' => $user->id,
        'name' => $user->name,
        'username' => $user->username,
        'avatar' => config('app.storage').$profile->profile_image,
        'url' => $profile->profile_url,
        'favorite_bible_verse' => $profile->favorite_bible_verse
    ];

    return $id;
}

});

From:

Echo.join(`worship_presence_channel.${id}`)
    .here((users) => {            
        worshipers=users;
        joinUser(worshipers);
        $('.group-count').html(worshipers.length);
        console.log(users);
    })
    .joining((user) => {
        worshipers.push(user);
        popupNewUser(user);
        joinUser(worshipers);
        $('.group-count').html(worshipers.length);
    })
    .leaving((user) => {
        worshipers = worshipers.filter(function(obj) {
            return (obj.id !== user.id);
        });
        popupLeaveUser(user);
        joinUser(worshipers);
        $('.group-count').html(worshipers.length);
    });

I also have an event which seems to be unneccassary but it lools like this:

public function broadcastOn()
{
    return new PresenceChannel('worship_presence_channel.58');
}

public function broadcastAs()
{
    return 'worship_presence_channel.58';
}

Can anyone please, tell me what i'm doing wrong or if I get the whole thing just wrong. Please help!


Solution

  • I've figured it out, I've change the echo codes above to this:

    Broadcast::channel('worship_presence_channel.{id}', function ($user, $id) {
    if(Auth()->check())
    {
        $profile = $user->Profile;
    
        $data = [
            'id' => $user->id,
            'name' => $user->name,
            'username' => $user->username,
            'avatar' => config('app.storage').$profile->profile_image,
            'url' => $profile->profile_url,
            'favorite_bible_verse' => $profile->favorite_bible_verse,
            'worships_id' => $id
        ];
    
        return $data;
    }
    

    });

    I'm passing 2 parameters $user, $id and it works just as the doc said it would!!!