
Learn how Implement Dependent Dropdowns in Livewire
Introduction
Implenting dependent dropdowns in any web app is a common requirement and there are cases where you'd need to implement dependent dropdowns in a Livewire based application.
In this article, we will learn how to implement dependent dropdowns in Livewire.
Prerequisites
I'm assuming that you have a basic understanding of Livewire and you have already installed Livewire in your Laravel application.
Configuration
To demonstrate this example, we will create a simple form with two dropdowns. The first dropdown will be for selecting the class(of a Student) and the second dropdown will be for selecting the Section.
So, let's start by creating a new Livewire Component called CreateStudent
We'll also pass the classes data, and whenever the class dropdown is changed, we'll fetch the sections of the selected class.
#[Validate('required')]
public $class_id;
public $sections = [];
public function render()
{
return view('livewire.create-student', [
'classes' => Classes::all(),
]);
}
We'll also define a few properties, to store the user selected values, like $class_id
, $section_id
and a $sections
property to store the sections of the selected class.
Let's look into the create-student.blade.php
file:
// dropdown for selecting the class
<select id="class_id" wire:model.live="class_id">
<option value="">Select a Class</option>
@foreach ($classes as $class)
<option value="{{ $class->id }}">
{{ $class->name }}
</option>
@endforeach
</select>
// dropdown for selecting the section
<select id="section_id" wire:model="section_id">
<option value="">Select a Section</option>
@foreach ($this->sections as $section)
<option value="{{ $section->id }}">
{{ $section->name }}
</option>
@endforeach
</select>
As you might've noticed, we're wire:modeling the class_id
and section_id
properties to the respective dropdowns, and one more thing to note here is we're wire:modeling the class_id
property with wire:model.live
instead of wire:model
.
Becuase by default, wire:model properties are deferred, and we want to fetch the sections of the selected class immediately, so we're using wire:model.live
here.
So, let's now hook into the updated lifecycle hook of the class_id
property and fetch the sections of the selected class.
public function updatedClassId($value)
{
$this->sections = Section::where('class_id', $value)->get();
}
So now, whenever the class dropdown is changed, the updatedClassId
method will be called and we'll fetch the sections of the selected class and store them in the $sections
property.
And since we're looping over the $sections
property in the blade file, the sections dropdown will be updated with the sections of the selected class.
I also want to mention the convention of naming the method updatedClassId
is important here, which is a combination of the livecycle hook (updated in this case), followed by the property name.
And that's it! We've successfully implemented dependent dropdowns in Livewire.