php 20 lines · 3 steps

Authorizing presence channels in Laravel

A broadcast channel callback gates access to a team channel and returns presence data for members.

Explained by highlit
1<?php
2 
3namespace App\Broadcasting;
4 
5use App\Models\Team;
6use App\Models\User;
7use Illuminate\Support\Facades\Broadcast;
8 
9Broadcast::channel('team.{team}', function (User $user, Team $team) {
10 if (! $user->belongsToTeam($team)) {
11 return false;
12 }
13 
14 return [
15 'id' => $user->id,
16 'name' => $user->name,
17 'avatar' => $user->avatar_url,
18 'role' => $team->roleFor($user),
19 ];
20});
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Channel callbacks double as gatekeepers: returning false denies subscription while a truthy value grants it.
  2. 2On presence channels, the returned array becomes the member's public identity shared with everyone else in the channel.
  3. 3Route-model binding resolves the channel's {team} placeholder into a full model before your logic runs.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Authorizing presence channels in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code