Presence Channels and When to Use It in Laravel Broadcasting

Hello Artisan

In this tutorial i will discuss about Public channels Private channels and Presence channels in Laravel Broadcasting. Do you know when to use Private channels and when to use Presence channels in Laravel broadcasting? 

Presence channels gives us additional feature build on the security of private channels.  We use private channels to get the authenticated users data. But when we will use presence channels its gives us some extra feature as well as private channels features.

 

Read aslo : Real Time Event Broadcasting with Laravel 7 and Pusher

 

When we want to make a user subscribed features then we can use presence channels rather than private channels. This makes it easy to build powerful, collaborative application features such as notifying users when another user is viewing the same page.

Keep in mind that all presence channels are also private channels. Therefore, users must be authorized to access them. By the way, when defining authorization callbacks for presence channels, you will not return true if the user is authorized to join the channel. Instead, you should return an array of data about the user. See the below code to understand: 

Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
    if ($user->canJoinRoom($roomId)) {
        return ['id' => $user->id, 'name' => $user->name];
    }
});

 

Read also : Real Time Chat App with Laravel 6 Vue Js and Pusher

 

To join a presence channel, you may use Echo's join method. The join method will return a PresenceChannel implementation which, along with exposing the listen method, allows you to subscribe to the herejoining, and leaving events.

Echo.join(`chat.${roomId}`)
    .here((users) => {
        //
    })
    .joining((user) => {
        console.log(user.name);
    })
    .leaving((user) => {
        console.log(user.name);
});

 

Remember the joining method will be executed when a new user joins a channel, while the leaving method will be executed when a user leaves the channel. Hope it can help you.

 

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website