Broadcasting
Framework-level broadcasting: fire event di backend, auto-delivered ke frontend via WebSocket. Laravel dan Node.js masing-masing punya pendekatan.
Laravel Broadcasting
// 1. Create Event
php artisan make:event OrderShipped
class OrderShipped implements ShouldBroadcast
{
public function __construct(public Order $order) {}
public function broadcastOn(): Channel
{
return new PrivateChannel("orders.{$this->order->user_id}");
}
public function broadcastWith(): array
{
return [
"orderId" => $this->order->id,
"status" => "shipped",
];
}
}
// 2. Fire event
event(new OrderShipped($order));
// Automatically broadcasts via Reverb/Pusher/Redis
Laravel Reverb (Built-in WebSocket Server)
// Install
composer require laravel/reverb
php artisan reverb:install
php artisan reverb:start
// Frontend (Laravel Echo)
import Echo from "laravel-echo";
import Pusher from "pusher-js";
window.Echo = new Echo({
broadcaster: "reverb",
key: import.meta.env.VITE_REVERB_APP_KEY,
wsHost: import.meta.env.VITE_REVERB_HOST,
wsPort: import.meta.env.VITE_REVERB_PORT,
});
// Listen
Echo.private(`orders.${userId}`).listen("OrderShipped", (e) => {
console.log("Order shipped:", e.orderId);
});
Node.js Pattern
// Event-driven broadcasting
class EventBroadcaster {
constructor(io) {
this.io = io;
}
toUser(userId, event, data) {
this.io.to(`user:${userId}`).emit(event, data);
}
toChannel(channelId, event, data) {
this.io.to(`ch:${channelId}`).emit(event, data);
}
toAll(event, data) {
this.io.emit(event, data);
}
}
// Usage in service
const broadcaster = new EventBroadcaster(io);
async function shipOrder(orderId) {
const order = await updateOrderStatus(orderId, "shipped");
broadcaster.toUser(order.userId, "order:shipped", {
orderId: order.id,
status: "shipped",
});
}