php
42 lines · 5 steps
How a broadcast event works in Laravel
A Laravel event pushes order status changes to a private WebSocket channel with a controlled payload.
Explained by
highlit
1<?php
2
3namespace App\Events;
4
5use App\Models\Order;
6use Illuminate\Broadcasting\Channel;
7use Illuminate\Broadcasting\InteractsWithSockets;
8use Illuminate\Broadcasting\PrivateChannel;
9use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
10use Illuminate\Foundation\Events\Dispatchable;
11use Illuminate\Queue\SerializesModels;
12
13class OrderStatusUpdated implements ShouldBroadcast
14{
15 use Dispatchable, InteractsWithSockets, SerializesModels;
16
17 public function __construct(public Order $order)
18 {
19 }
20
21 public function broadcastOn(): array
22 {
23 return [
24 new PrivateChannel('orders.'.$this->order->customer_id),
25 ];
26 }
27
28 public function broadcastAs(): string
29 {
30 return 'order.status.updated';
31 }
32
33 public function broadcastWith(): array
34 {
35 return [
36 'id' => $this->order->id,
37 'status' => $this->order->status,
38 'total' => $this->order->total_amount,
39 'updated_at' => $this->order->updated_at->toIso8601String(),
40 ];
41 }
42}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing ShouldBroadcast turns a plain event into one that streams over WebSockets when dispatched.
- 2broadcastWith lets you send a lean, curated payload instead of the whole serialized model.
- 3Private channels scoped to a user id keep real-time updates authorized and per-customer.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-broadcast-event-works-in-laravel-explained-php-fcd0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.