Broadcasting
| Events over websockets | |
| Broadcast event sketch | |
| Listen on frontend | |
| Driver note |
Events over websockets
HTTP answers only when asked: the browser sends a request and Laravel returns a response. Real-time features flip the direction - when an order ships on the server, every open dashboard learns about it within a second, with nobody pressing refresh.
Broadcasting is the bridge: your code fires an event, Laravel pushes it through a websocket driver, and JavaScript listeners update the page. Think of it as a radio station where the server transmits and browsers tune in.
Broadcast event sketch
A broadcast event is a plain PHP class that carries public data and names the channel it belongs to. The ShouldBroadcast marker tells Laravel to push it to the socket layer instead of handling it only inside the current process.
namespace App\Events; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class OrderShipped implements ShouldBroadcast { public function __construct(public int $orderId) { } public function broadcastOn(): array { return ["orders"]; } }
Listen on frontend
On the browser side a tiny JavaScript sketch subscribes to the same channel name and reacts when the event arrives. Channel names must match letter for letter, or the listener waits in silence.
Echo.channel("orders").listen("OrderShipped", (e) => { console.log("Shipped order " + e.orderId); });
Driver note
During development use the log driver, which writes every broadcast to the log file instead of opening sockets. The event code stays identical - only the driver setting changes when real traffic needs real websockets.
Keep the channel names stable from day one. Renaming a channel later means updating the event class and every JavaScript listener at the same time, which is exactly the kind of flag day worth avoiding.
Next: Full-text search
Article author: Arthur Isaev