Laravel Livewire | Laravel Framework | PHP & MySQL | Tutorials

David Carr

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.  

Detailed video explanation / demo:

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

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>

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

Now the contacts list changes when the client 

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.