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:

            
1class OrderShipped implements ShouldBroadcast
2{
3 use Dispatchable, InteractsWithSockets, SerializesModels;
4 
5 public function broadcastOn()
6 {
7 return new Channel('orders');
8 }
9}

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

        
1event(new OrderShipped);

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

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

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.

            
1class OrderTracker extends Component
2{
3 public $showNewOrderNotification = false;
4 
5 // Special Syntax: ['echo:{channel},{event}' => '{method}']
6 protected $listeners = ['echo:orders,OrderShipped' => 'notifyNewOrder'];
7 
8 public function notifyNewOrder()
9 {
10 $this->showNewOrderNotification = true;
11 }
12}

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.
            
1class OrderTracker extends Component
2{
3 public $showNewOrderNotification = false;
4 public $orderId;
5 
6 public function mount($orderId)
7 {
8 $this->orderId = $orderId;
9 }
10 
11 public function getListeners()
12 {
13 return [
14 "echo-private:orders.{$this->orderId},OrderShipped" => 'notifyNewOrder',
15 // Or:
16 "echo-presence:orders.{$this->orderId},OrderShipped" => 'notifyNewOrder',
17 ];
18 }
19 
20 public function notifyNewOrder()
21 {
22 $this->showNewOrderNotification = true;
23 }
24}
← Previous Topic

AlpineJS

Next Topic →

Inline Scripts