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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing ShouldBroadcast turns a plain event into one that streams over WebSockets when dispatched.
  2. 2broadcastWith lets you send a lean, curated payload instead of the whole serialized model.
  3. 3Private channels scoped to a user id keep real-time updates authorized and per-customer.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a broadcast event works in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code