Laravel Livewire update dependent select menu's on change

David Carr

Laravel Framework Tutorials PHP & MySQL Laravel Livewire

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:

<iframe frameborder="0" height="315" src="https://www.youtube.com/embed/JXtZdnUv7IE" title="YouTube video player" width="560"></iframe>

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 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Fathom Analytics $10 discount on your first invoice using this link

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.