【Laravel實戰】15分鐘搞懂Livewire整合Echo

【Laravel實戰】15分鐘搞懂Livewire整合Echo

Livewire 與 Laravel Echo 的完美搭配,可使用 WebSocket 在你的網頁上提供實時功能

此功能假定你已經安裝了 Laravel Echo ,並且 window.Echo 物件為全域。有關更多資訊請查看文檔

考慮以下Laravel事件:

class OrderShipped implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function broadcastOn()
    {
        return new Channel('orders');
    }
}

比如你觸發 Laravel 廣播系統的事件:

event(new OrderShipped);

一般來說,你會像這樣來偵聽 Laravel Echo 的事件:

Echo.channel('orders')
        .listen('OrderShipped', (e) => {
            console.log(e.order.name);
        });

但是使用 Livewire ,你要做的就只是在 $listeners 屬性中註冊它,並使用一些特殊的語法來指定它源自於Echo

//app/Http/Livewire/OrderTracker.php

class OrderTracker extends Component
{
    public $showNewOrderNotification = false;

    // Special Syntax: ['echo:{channel},{event}' => '{method}']
    protected $listeners = ['echo:orders,OrderShipped' => 'notifyNewOrder'];

    public function notifyNewOrder()
    {
        $this->showNewOrderNotification = true;
    }
}

現在 Livewire 將攔截從 Pusher 收到的事件,並採取相應的措施。以類似的方式,你還可以收聽廣播到私人/狀態頻道的事件,但請確保正確定義了身份驗證的回呼函式

//app/Http/Livewire/OrderTracker.php

class OrderTracker extends Component
{
    public $showNewOrderNotification = false;
    public $orderId;

    public function mount($orderId)
    {
        $this->orderId = $orderId;
    }

    public function getListeners()
    {
        return [
            "echo-private:orders.{$this->orderId},OrderShipped" => 'notifyNewOrder',
            // Or:
            "echo-presence:orders.{$this->orderId},OrderShipped" => 'notifyNewOrder',
        ];
    }

    public function notifyNewOrder()
    {
        $this->showNewOrderNotification = true;
    }
}

分享這篇文章:

關聯文章:

訂閱電子報,索取 Laravel 學習手冊

價值超過 3000 元,包含常用 Laravel 語法與指令!

Laravel 百萬年薪特訓營

從最基礎的 PHP 語法開始,包含所有你該知道的網頁基礎知識,連同 Laravel 從零開始一直到實戰,最後還將告訴你如何找好工作,讓你及早擁有百萬年薪