You're browsing the documentation for an old version of Livewire. Consider upgrading your project to Livewire 3.x.

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.

            
1use Livewire\Component;
2 
3class OrderTracker extends Component
4{
5 public $showNewOrderNotification = false;
6 
7 // Special Syntax: ['echo:{channel},{event}' => '{method}']
8 protected $listeners = ['echo:orders,OrderShipped' => 'notifyNewOrder'];
9 
10 public function notifyNewOrder()
11 {
12 $this->showNewOrderNotification = true;
13 }
14 
15 public function render()
16 {
17 return view('livewire.order-tracker');
18 }
19}

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.
            
1use Livewire\Component;
2 
3class OrderTracker extends Component
4{
5 public $showNewOrderNotification = false;
6 public $orderId;
7 
8 public function mount($orderId)
9 {
10 $this->orderId = $orderId;
11 }
12 
13 public function getListeners()
14 {
15 return [
16 "echo-private:orders.{$this->orderId},OrderShipped" => 'notifyNewOrder',
17 // Or:
18 "echo-presence:orders.{$this->orderId},OrderShipped" => 'notifyNewOrder',
19 ];
20 }
21 
22 public function notifyNewOrder()
23 {
24 $this->showNewOrderNotification = true;
25 }
26 
27 public function render()
28 {
29 return view('livewire.order-tracker');
30 }
31}
← Previous Topic Turbolinks
Next Topic → Inline Scripts