DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

Laravel Livewire update dependent select menu's on change

Since Livewire is reactive, it's easy to hide or show select menu's based on whether another one is selected but what about changing the contents of a select menu, that's a little different.

Take this use case, you have clients and contacts, each client has its own unique list of contacts. You want to select a client and then select a client.

In a Livewire component use the mount method to load up the client and that contacts based on a selected client


public function mount()
{
    if ($this->clientId !='') {
        $this->contacts = Contact::where('client_id', $this->clientId)->get();
    }
}
Enter fullscreen mode Exit fullscreen mode

Then in the view show the list of contacts in a select menu, when no client is selected the list would be empty.


<select name="contactId" wire:model="contactId" label="Contact">
    @foreach($contacts as $contact)
        <option value="{{ $contact->id }}">{{ $contact->name }}</option>
    @endforeach
</select>
Enter fullscreen mode Exit fullscreen mode

So far so good but if the client changes the contacts list won't change due the contacts already been mounted.

What you can do is listen for an updated event, create a method call updated followed by the property name. If the property is called clientId then the method should be called updatedClientId()

When this method fires change the list of contacts which will change in the view since Livewire re-renders are every change,


public function updatedClientId()
{
    $this->contacts = Contact::where('client_id', $this->clientId)->get();
}
Enter fullscreen mode Exit fullscreen mode

Now the contacts list changes when the client

Top comments (0)