Courses

Livewire 3 From Scratch: Practical Course

Dependent Dropdowns: Country and Cities

Summary of this lesson:
- Implementing country-city relationship in database
- Creating dynamic dropdown components
- Using wire:model.live for instant updates
- Handling dependent select fields

In this course section, we will build four small demo projects to practice Livewire more. The first project is a dependent dropdown, like a parent and a child.

When we will choose a country, the cities list will be refreshed.

dependent dropdowns


DB Structure

First, let's quickly see what the Migrations and Models look like.

database/migrations/xxx_create_countries_table.php:

Schema::create('countries', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});

app/Models/Country.php:

use Illuminate\Database\Eloquent\Relations\HasMany;
 
class Country extends Model
{
protected $fillable = [
'name',
];
 
public function cities(): HasMany
{
return $this->hasMany(City::class);
}
}

database/migrations/xxx_create_cities_table.php:

Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->foreignId('country_id');
$table->string('name');
$table->timestamps();
});

app/Models/City.php:

class City extends Model
{
protected $fillable = [
'country_id',
'name',
];
}

And a simple seeder to have some data in the DB:

$country = Country::create(['name' => 'United Kingdom']);
$country->cities()->create(['name' => 'London']);
$country->cities()->create(['name' => 'Manchester']);
$country->cities()->create(['name' => 'Liverpool']);
 
$country = Country::create(['name' => 'United States']);
$country->cities()->create(['name' => 'Washington']);
$country->cities()->create(['name' => 'New York City']);
$country->cities()->create(['name' => 'Denver']);

Livewire Component

For the Livewire component, we will name it just Dropdowns.

php artisan make:livewire Dropdowns

In the component, we first must get the list of...

The full lesson is only for Premium Members.
Want to access all 30 lessons of this course? (108 min read)

You also get:

  • 73 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord