Welcome to my tutorial on creating a Laravel 10 Vue 3 Dependent Dropdown example! In this guide, I'll walk you through building a dynamic dropdown functionality using Laravel 10 on the backend and Vue 3 on the front end.
Dependent dropdowns are a crucial aspect of many web applications, especially those dealing with location-based data. They allow users to select options dynamically based on the previous selection, providing a seamless and intuitive experience.
We'll focus on a common scenario with three dropdowns: Country, State, and City.
So, let's see the laravel 10 vue 3 dependent dropdown example, how to create a dependent dropdown in laravel 10 vue 3, dependent dropdown in vue js, dependent dropdown vue js, and laravel 8/9/10.
Here's an example of how to create a dependent dropdown with Vue.js and Laravel 10:
Install Laravel 10 by running the following command in your terminal:
composer create-project --prefer-dist laravel/laravel project-name
Navigate to your project directory.
cd project-name
-
Before we begin, ensure your database credentials are properly configured in the
.env
file.To set up the necessary tables in your database, follow these steps:
- Create three tables in your database:
countries
,states
, andcities
. Each table should have anid
(primary key) andname
column to store relevant data. - Populate these tables with appropriate data using database seeding.
Now, to generate the migrations for the countries
, states
, and cities
tables in Laravel, proceed as follows:
Run the following command to create a migration for the countries
table:
php artisan make:migration create_countries_table --create=countries
This will generate a new migration file in the database/migrations
directory. Open the generated file and modify it by adding the following code.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCountriesTable extends Migration
{
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('countries');
}
}
Repeat the above steps to create migrations for the states
and cities
tables.
For the states
table.
php artisan make:migration create_states_table --create=states
Update the generated migration file with the following code.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStatesTable extends Migration
{
public function up()
{
Schema::create('states', function (Blueprint $table) {
$table->id();
$table->foreignId('country_id')->constrained('countries')->onDelete('cascade');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('states');
}
}
For the cities
table.
php artisan make:migration create_cities_table --create=cities
Update the generated migration file with the following code.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCitiesTable extends Migration
{
public function up()
{
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->foreignId('state_id')->constrained('states')->onDelete('cascade');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('cities');
}
}
Save the migration files and rerun the migrations.
php artisan migrate
Now, the countries
, states
, and cities
tables will be created in your database with the respective columns.
Set up routes in routes/web.php
to handle the retrieval of data for the dropdowns
use App\Http\Controllers\DropdownController;
Route::get('/countries', [DropdownController::class, 'getCountries']);
Route::get('/states/{countryId}', [DropdownController::class, 'getStates']);
Route::get('/cities/{stateId}', [DropdownController::class, 'getCities']);
To create a controller named DropdownController
, execute the following command:
php artisan make:controller DropdownController
Open the generated DropdownController.php
file and replace its contents with the following code.
namespace App\Http\Controllers;
use App\Models\Country;
use App\Models\State;
use App\Models\City;
class DropdownController extends Controller
{
public function getCountries()
{
$countries = Country::all();
return response()->json($countries);
}
public function getStates($countryId)
{
$states = State::where('country_id', $countryId)->get();
return response()->json($states);
}
public function getCities($stateId)
{
$cities = City::where('state_id', $stateId)->get();
return response()->json($cities);
}
}
Create a new Vue component called Dropdown.vue
in the resources/js/components
directory.
Next, update the Dropdown.vue
component with the following code.
<template>
<div>
<select v-model="selectedCountry" @change="getStates">
<option value="">Select Country</option>
<option v-for="country in countries" :key="country.id" :value="country.id">{{ country.name }}</option>
</select>
<select v-model="selectedState" @change="getCities">
<option value="">Select State</option>
<option v-for="state in states" :key="state.id" :value="state.id">{{ state.name }}</option>
</select>
<select v-model="selectedCity">
<option value="">Select City</option>
<option v-for="city in cities" :key="city.id" :value="city.id">{{ city.name }}</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
countries: [],
states: [],
cities: [],
selectedCountry: '',
selectedState: '',
selectedCity: '',
};
},
mounted() {
this.getCountries();
},
methods: {
getCountries() {
axios.get('/countries')
.then(response => {
this.countries = response.data;
})
.catch(error => {
console.log(error);
});
},
getStates() {
axios.get('/states/' + this.selectedCountry)
.then(response => {
this.states = response.data;
this.selectedState = '';
this.cities = [];
this.selectedCity = '';
})
.catch(error => {
console.log(error);
});
},
getCities() {
axios.get('/cities/' + this.selectedState)
.then(response => {
this.cities = response.data;
this.selectedCity = '';
})
.catch(error => {
console.log(error);
});
},
},
};
</script>
Open the resources/views/welcome.blade.php
file and replace its contents with the following code snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel Vue3 Dependent Dropdown Example - Vidvatek</title>
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<dropdown></dropdown>
</div>
<script src="{{ mix('js/app.js') }}"></script>
</body>
</html>
To compile the assets, run the following command:
npm install && npm run dev
To initiate the Laravel development server, execute the following command in your terminal:
php artisan serve
Now, when you navigate to the localhost URL, you'll encounter the dependent dropdowns for country, state, and city. Upon selecting a country, the corresponding states will dynamically load, and selecting a state will trigger the loading of relevant cities.
Ensure that you verify the consistency of your database configuration, table names, and model names with your application. Adjust the code accordingly to match your specific setup.
Moreover, you may require Axios installation if it's not already included in your project. You can do so by executing npm install axios.
You might also like:
- Read Also: Laravel 10 With Vue JS CRUD Operation
- Read Also: How to Create Modal in Laravel 10 Livewire
- Read Also: How to Create Autocomplete Search in Vue JS
- Read Also: How to use Unique Validation on Update in Laravel 10