Polyscope - The agent-first dev environment for Laravel

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 Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
Shift logo

Shift

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

Shift
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
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
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Lucky Media logo

Lucky Media

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

Lucky Media
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
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
SerpApi logo

SerpApi

Access real-time search engine results through a simple API—no more scraping headaches! Use it for AI applications, SEO tools, product research, travel information, and more

SerpApi

The latest

View all →
Simple Feature Flags for Laravel with Laravel Toggle image

Simple Feature Flags for Laravel with Laravel Toggle

Read article
Manage Laravel Cloud Deployments Inside PhpStorm image

Manage Laravel Cloud Deployments Inside PhpStorm

Read article
Piper: Laravel-Style Array and String Helpers for PHP's Pipe Operator image

Piper: Laravel-Style Array and String Helpers for PHP's Pipe Operator

Read article
Storage Cache Store in Laravel 13.10.0 image

Storage Cache Store in Laravel 13.10.0

Read article
Laravel MongoDB Full-Text Search tutorial: The Art of the Relevancy image

Laravel MongoDB Full-Text Search tutorial: The Art of the Relevancy

Read article
Drag-and-Drop Sorting for Eloquent Models with Reorderable for Laravel image

Drag-and-Drop Sorting for Eloquent Models with Reorderable for Laravel

Read article