约 2 分钟阅读
实时广播与 Reverb (Broadcasting)
在现代 Web 应用中,WebSocket 用于实现实时通知、在线聊天和即时数据大屏。Laravel 提供了官方第一方 WebSocket 服务器 Laravel Reverb,无需额外依赖外部付费服务。
创建可广播事件
namespace App\Events;
use App\Models\Order;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
class OrderShipped implements ShouldBroadcast
{
use Dispatchable;
public function __construct(public Order $order) {}
public function broadcastOn(): array
{
return [
new PrivateChannel('orders.'.$this->order->user_id),
];
}
}
前端接收广播 (Laravel Echo)
import Echo from 'laravel-echo';
window.Echo.private(`orders.${userId}`)
.listen('OrderShipped', (e) => {
console.log('订单状态更新:', e.order);
});