Laravel Livewire update dependent select menus on change

Laravel Livewire update dependent select menus on change

David Carr

2 min read - 12th Sep, 2021

Laravel Laravel-livewire

Since Livewire is reactive, it's easy to hide or show select menus 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.

@foreach($contacts as $contact)
    {{ $contact->name }}
@endforeach

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

What you can do is listen for an updated event, and create a method called 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.

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.