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 & 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
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
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
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
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 →
Laravel Fuse: A Circuit Breaker Package for Queue Jobs image

Laravel Fuse: A Circuit Breaker Package for Queue Jobs

Read article
Generate Complete Application Modules with a Single Command using Laravel TurboMaker image

Generate Complete Application Modules with a Single Command using Laravel TurboMaker

Read article
`hasSole()` Collection Method in Laravel 12.49.0 image

`hasSole()` Collection Method in Laravel 12.49.0

Read article
Install Laravel Package Guidelines and Skills in Boost image

Install Laravel Package Guidelines and Skills in Boost

Read article
Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce image

Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce

Read article
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article