Single component events in Laravel Livewire

Matthew Erwin • January 30, 2021

laravel livewire

When rendering multiple instances of the same Livewire component on a page you may want to emit an event to a specific child component, not all components of the same type.

Take for example this page:

<livewire:product sku="1">
<livewire:product sku="2">
<livewire:product sku="3">
class Product extends Component
{
    public $sku;

    protected $listeners = [
        'productUpdated' => '$refresh',
    ];

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

    public function render()
    {
        return view('livewire.product');
    }
}

If we fire the productUpdated event then we will see that this results in 3 HTTP requests since each of the 3 components need to be refreshed. Multiple HTTP Request

If we specify custom listeners in the component then we can target a specific component without refreshing the rest.

class Product extends Component
{
    ...

    protected function getListeners()
    {
        return ['productUpdated:' . $this->sku => '$refresh'];
    }
}

Single HTTP Request

This approach has also been recommended by Caleb Porzio, the author of Livewire. https://github.com/livewire/livewire/issues/845#issuecomment-652082535

Note

Currently if you remove one of the events and then trigger the event you will get an undefined index error. See Issue #2401.