Tinkerwell - The PHP Scratchpad

Creating Dynamic Real-Time Features with Laravel Broadcasting

Last updated on by

Creating Dynamic Real-Time Features with Laravel Broadcasting image

Laravel's broadcasting system empowers developers to build responsive, real-time applications that deliver instant updates to users. From live dashboards to collaborative workspaces, broadcasting transforms static applications into dynamic, interactive experiences.

Event Broadcasting Implementation

Create broadcastable events by implementing the ShouldBroadcast interface:

<?php
 
namespace App\Events;
 
use App\Models\Project;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
 
class ProjectStatusUpdated implements ShouldBroadcast
{
use SerializesModels;
 
public function __construct(
public Project $project
) {}
 
public function broadcastOn(): array
{
return [
new PrivateChannel('projects.' . $this->project->id),
];
}
 
public function broadcastWith(): array
{
return [
'project_id' => $this->project->id,
'status' => $this->project->status,
'updated_at' => $this->project->updated_at,
];
}
}

Dispatch the event to trigger broadcasting:

ProjectStatusUpdated::dispatch($project);

Channel Authorization

Define channel access rules in routes/channels.php:

use App\Models\Project;
use App\Models\User;
 
Broadcast::channel('projects.{projectId}', function (User $user, int $projectId) {
$project = Project::find($projectId);
return $user->id === $project->owner_id || $user->projects->contains($projectId);
});

Consider a collaborative project management platform where team members need instant updates on task progress, file uploads, and team communications. Real-time features enhance productivity by eliminating the need for manual refreshes:

<?php
 
namespace App\Events;
 
use App\Models\Task;
use App\Models\Team;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
 
class TaskAssigned implements ShouldBroadcast
{
public function __construct(
public Task $task,
public Team $team
) {}
 
public function broadcastOn(): array
{
return [
new PrivateChannel('users.' . $this->task->assigned_to),
new PresenceChannel('teams.' . $this->team->id),
];
}
 
public function broadcastWith(): array
{
return [
'task' => [
'id' => $this->task->id,
'title' => $this->task->title,
'priority' => $this->task->priority,
'due_date' => $this->task->due_date,
],
'assignee' => $this->task->assignee->name,
'project' => $this->task->project->name,
];
}
}
 
class FileUploaded implements ShouldBroadcast
{
public function __construct(
public $file,
public $project
) {}
 
public function broadcastOn(): array
{
return [
new PrivateChannel('projects.' . $this->project->id),
];
}
 
public function broadcastAs(): string
{
return 'file.uploaded';
}
}
 
class TeamMemberActive implements ShouldBroadcast
{
public function __construct(
public $user,
public $team
) {}
 
public function broadcastOn(): array
{
return [
new PresenceChannel('team-workspace.' . $this->team->id),
];
}
}

Channel authorization ensures secure access to sensitive project data:

// routes/channels.php
use App\Models\User;
 
Broadcast::channel('users.{userId}', function (User $user, int $userId) {
return $user->id === $userId;
});
 
Broadcast::channel('teams.{teamId}', function (User $user, int $teamId) {
return $user->teams->contains($teamId) ? [
'id' => $user->id,
'name' => $user->name,
'avatar' => $user->avatar_url,
'role' => $user->teams()->find($teamId)->pivot->role,
] : false;
});
 
Broadcast::channel('team-workspace.{teamId}', function (User $user, int $teamId) {
if ($user->teams->contains($teamId)) {
return [
'id' => $user->id,
'name' => $user->name,
'status' => $user->current_status,
'last_seen' => now(),
];
}
return false;
});

Client-Side Integration

Configure Laravel Echo for real-time event listening:

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
 
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_PUSHER_APP_KEY,
cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
forceTLS: true
});
 
Echo.private(`users.${userId}`)
.listen('TaskAssigned', (e) => {
showNotification(`New task assigned: ${e.task.title}`);
updateTaskList(e.task);
});
 
Echo.join(`team-workspace.${teamId}`)
.here((users) => {
displayActiveTeamMembers(users);
})
.joining((user) => {
addActiveUser(user);
showAlert(`${user.name} joined the workspace`);
})
.leaving((user) => {
removeActiveUser(user);
showAlert(`${user.name} left the workspace`);
})
.listen('TaskAssigned', (e) => {
updateTeamActivity(e);
});
 
Echo.private(`projects.${projectId}`)
.listen('.file.uploaded', (e) => {
refreshFileList();
showNotification('New file uploaded to project');
});
 
Echo.private(`projects.${projectId}`)
.whisper('typing', {
user: currentUser.name,
section: 'comments'
})
.listenForWhisper('typing', (e) => {
showTypingIndicator(e.user, e.section);
});

Advanced Broadcasting Features

Laravel supports immediate broadcasting for critical updates:

class UrgentSystemAlert implements ShouldBroadcastNow
{
public function broadcastOn(): array
{
return [
new Channel('system-alerts'),
];
}
}

Broadcasting transforms web applications from static pages into dynamic, collaborative platforms. By implementing real-time features, you create engaging user experiences that keep teams synchronized and workflows efficient.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Improved Skill and Guideline Detection in Laravel Boost v2.2.0 image

Improved Skill and Guideline Detection in Laravel Boost v2.2.0

Read article
"The Vibes" — NativePHP Hosts a Day 3 after Laracon US image

"The Vibes" — NativePHP Hosts a Day 3 after Laracon US

Read article
What We Know About Laravel 13 image

What We Know About Laravel 13

Read article
New Colors Added in Tailwind CSS v4.2 image

New Colors Added in Tailwind CSS v4.2

Read article
Factory makeMany() Method in Laravel 12.52.0 image

Factory makeMany() Method in Laravel 12.52.0

Read article
Laravel Adds an Official Svelte + Inertia Starter Kit image

Laravel Adds an Official Svelte + Inertia Starter Kit

Read article