Laravel Echo

Livewire pairs nicely with Laravel Echo to provide real-time functionality on your web-pages using WebSockets.

This feature assumes you have installed Laravel Echo and the `window.Echo` object is globally available. For more info on this, check out the docs.

Consider the following Laravel Event:

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

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

Let's say you fire this event with Laravel's broadcasting system like this:

event(new OrderShipped);

Normally, you would listen for this event in Laravel Echo like so:

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

With Livewire however, all you have to do is register it in your $listeners property, with some special syntax to designate that it originates from Echo.

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;
    }
}

Now, Livewire will intercept the received event from Pusher, and act accordingly. In a similar way, you can also listen to events broadcasted to private/presence channels:

Make sure you have your Authentication Callbacks properly defined.
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;
    }
}
← Previous Topic

AlpineJS

Next Topic →

Inline Scripts