Code review at scale is broken. Here’s how Augment Code is fixing it.

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 Writer @ Laravel News • PHP, Laravel, Livewire, TailwindCSS, VueJS & InertiaJS • Co-organizer @ Laravel Greece Meetup

Cube

Laravel Newsletter

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

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
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
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
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
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 →
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article
Handle Nested Data Structures in PHP with the Data Block Package image

Handle Nested Data Structures in PHP with the Data Block Package

Read article
Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup image

Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup

Read article
Seamless PropelAuth Integration in Laravel with Earhart image

Seamless PropelAuth Integration in Laravel with Earhart

Read article
Laravel API Route image

Laravel API Route

Read article
Laravel News 2025 Recap image

Laravel News 2025 Recap

Read article