Chuyển đến nội dung chính

Lesson 14: Events, Listeners & Broadcasting

Event system, event subscribers. Broadcasting with Pusher/Laravel Reverb. Private/presence channels. Real-time notifications, WebSocket integration. Laravel Echo.

💻 Programming — Lesson 14 Lesson 14: Events, Listeners & Broadcasting

Laravel: From Basics to Advanced

Part 4: Advanced Features

xdev.asia

1. Events & Listeners

// Event
class OrderPlaced
{
    use Dispatchable, SerializesModels;

    public function __construct(
        public readonly Order $order,
    ) {}
}

// Listener
class SendOrderConfirmation implements ShouldQueue
{
    public function handle(OrderPlaced $event): void
    {
        $event->order->user->notify(new OrderConfirmation($event->order));
    }
}

// EventServiceProvider hoặc Attribute
#[AsEventListener]
class SendOrderConfirmation { ... }

// Dispatch
OrderPlaced::dispatch($order);
event(new OrderPlaced($order));

2. Broadcasting

composer require laravel/reverb
php artisan reverb:install
class OrderStatusUpdated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(
        public readonly Order $order,
    ) {}

    public function broadcastOn(): array
    {
        return [new PrivateChannel('orders.' . $this->order->user_id)];
    }

    public function broadcastWith(): array
    {
        return [
            'order_id' => $this->order->id,
            'status' => $this->order->status,
        ];
    }
}

// routes/channels.php
Broadcast::channel('orders.{userId}', function (User $user, int $userId) {
    return $user->id === $userId;
});

3. Laravel Echo (Frontend)

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

const 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,
    forceTLS: false,
});

echo.private(`orders.${userId}`)
    .listen('OrderStatusUpdated', (e) => {
        console.log('Order updated:', e.order_id, e.status);
    });

// Presence channel
echo.join(`chat.${roomId}`)
    .here((users) => console.log('Online:', users))
    .joining((user) => console.log('Joined:', user))
    .leaving((user) => console.log('Left:', user));

Next article: Notifications, Mail & Scheduler.