Technology

Presence Channels in Laravel

Auctibles is a sale events platform that generates a multiplayer game experience by showing playful notifications whenever users enter the event.

Such an experience can be created in the Laravel PHP framework through presence channels.

#Channels

The presence of authenticated users is broadcast in Laravel on private presence channels.

In routes/channels.php,

Broadcast::channel('room.{room}', function (User $user, Room $room) {
        return ['id' => $user->id, 'role' => session('role'), 'name' => $user->full_name];            
});

#Listeners

In Livewire, we define listeners to the presence events:

private function presence_listeners()
{
return [
    "echo-presence:room.{$this->room->id},here" => 'hereOnline',
    "echo-presence:room.{$this->room->id},joining" => 'joinOnline',
    "echo-presence:room.{$this->room->id},leaving" => 'leaveOnline', 
    "echo-presence:room.{$this->room->id},error" => 'errorOnline', 
];
}

#Processing Presence Information

We show a toast using livewire-toaster whenever we receive a notification on users entering or leaving an event.

We define a trait to be used on all screens relevant to the event. The screens are built using Livewire.

We use Toast::warn to have the desired color.

use Masmerise\Toaster\Toaster;

trait EventRoomPresenceTrait {

    public $count_users_online = 0;

    public function hereOnline($data) {
	   
	    // show only consumers, not sellers
    $this->count_users_online = 
    collect($data)
    ->filter(function($user) {
        return $user['role'] == 'consumer';
    })
    ->count();
    }

    public function joinOnline($data) {
    $this->count_users_online = $this->count_users_online + 1;
        
    // show a toast that someone joined
    Toaster::warning(trans('expressions.:name joined the event', ['name' => $data['name']]) . " \u{1F6AA} \u{1F6B6}");
     
    }

    public function leaveOnline($data) {
    $this->count_users_online = $this->count_users_online - 1;
	
			// show a toast that someone left
    Toaster::warning(trans('expressions.:name left the event', ['name' => $data['name']]) . " \u{1F31E} \u{1F333} \u{1F6B6}");
    }

    public function errorOnline($data) {
        logger()->debug('error', ['data' => $data]);
    }

#The View

We show the number of active users in each view relevant to the event.

	<h2 class="text-center text-lg font-medium">
    {{ $count_users_online }} Online Users
  </h2>
Yoram Kornatzky

Yoram Kornatzky