使用 Laravel Websocket 监听数据库

Database listening with Laravel Websocket

我已经完成了所有与 Laravel Websocket 相关的安装。这是我正在尝试做的事情:我在保存订单的数据库中有一个 table。当有新订单到达时,我想将其打印到主页上的控制台 blade。

如果你能帮上忙,我会很高兴。谢谢

您可以在订单模型中使用如下模型事件

protected static function booted()
{
    //everytime when new order is created this function will be called
    static::created(function ($order) {
        //then broadcast event
        NewOrder::dispatch($order);
    });
}

然后您必须在 route/channel 中定义频道。php

use App\Models\Order;

Broadcast::channel('newOrder', function ($user) {
   return $user->id;
});

然后创建事件php artisan make:event NewOrder

class NewOrder implements ShouldBroadcast
{

/**
 * The user that created the server.
 *
 * @var \App\Models\User
 */
public $user;

/**
 * Create a new event instance.
 *
 * @param  \App\Models\User  $user
 * @return void
 */
public function __construct(User $user)
{
    $this->user = $user;
}

/**
 * Get the channels the event should broadcast on.
 *
 * @return Channel|array
 */
public function broadcastOn()
{
    return new PrivateChannel('newOrder');
}
}

然后在newOrder Channel中监听NewOrder事件

Echo.channel(`newOrder`)
.listen('NewOrder', (e) => {
    console.log(e.order);
});

阅读文档更多信息https://laravel.com/docs/9.x/broadcasting#pusher-channels