Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

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
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
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
PhpStorm logo

PhpStorm

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

PhpStorm
Laravel Cloud logo

Laravel Cloud

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

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

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Laravel Starter Kits Now Include Toast Notifications image

Laravel Starter Kits Now Include Toast Notifications

Read article
Ship AI with Laravel: Stop Your AI Agent from Guessing image

Ship AI with Laravel: Stop Your AI Agent from Guessing

Read article
Laravel Cloud Adds Path Blocking to Prevent Bots From Waking Hibernated Apps image

Laravel Cloud Adds Path Blocking to Prevent Bots From Waking Hibernated Apps

Read article
Making Laravel MongoDB Operations Idempotent: Safe Retries for Financial Transactions image

Making Laravel MongoDB Operations Idempotent: Safe Retries for Financial Transactions

Read article
FormRequest Strict Mode and Queue Job Inspection in Laravel 13.4.0 image

FormRequest Strict Mode and Queue Job Inspection in Laravel 13.4.0

Read article
Pretty PHP Info: A Modern Replacement for `phpinfo()` image

Pretty PHP Info: A Modern Replacement for `phpinfo()`

Read article