Overview
Implement Presence Channels in Laravel 11 Using Laravel Reverb & Laravel Echo
Presence channels allow you to track which users are online in real-time. This is useful for chat apps, user activity tracking, and more.
Step 1: Define Presence Channel in routes/channels.php
Modify routes/channels.php
to authenticate users when they join the presence channel.
use Illuminate\Support\Facades\Broadcast;
Broadcast::channel('online-users', function ($user) {
return ['id' => $user->id, 'name' => $user->name]; // Expose user info
});
๐ก This ensures that only authenticated users can join and their info is shared with other members.
Step 2: Update Laravel Echo to Use Presence Channel
Modify your JavaScript frontend code to listen for users joining/leaving:
window.Echo.join("online-users")
.here((users) => {
console.log("Currently online users:", users);
}).joining((user) => {
console.log(user.name + " joined the chat.");
}).leaving((user) => {
console.log(user.name + " left the chat.");
}).error((error) => {
console.error("Presence channel error:", error);
});
๐ก What happens here?
.here(users)
โ Lists all currently online users.joining(user)
โ Detects when a new user joins.leaving(user)
โ Detects when a user leaves
Step 3: Configure Echo Authentication
Modify resources/js/bootstrap.js
to support presence authentication:
import Echo from "laravel-echo";
import Pusher from "pusher-js";
window.Echo = new Echo({
broadcaster: "pusher",
key: "anykey", // Not needed for Reverb
wsHost: window.location.hostname,
wsPort: 6001, forceTLS: false,
disableStats: true,
authEndpoint: "/broadcasting/auth",
auth: {
headers: {
Authorization: `Bearer ${localStorage.getItem("auth_token")}`,
"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
},
},
});
Step 4: Restart Everything
Run these commands to clear the cache and start all services:
php artisan cache:clear
php artisan config:clear
php artisan reverb:start
npm run dev
php artisan serve
Step 5: Test Presence Channels
- Open two browser tabs
- Login with two different users
- Check the browser console (F12 > Console)
- You should see currently online users
- When a user joins or leaves, it should log updates
โ Final Presence Channel Summary
โ
Track online users in real-time
โ
Only authenticated users can join
โ
Shows users when they join/leave
โ
Works seamlessly with Laravel Reverb & Echo
Here is how you see the list of online users in the UI? ๐