How to Create a Dependent Dropdown List in Laravel
Hello learners, in this tutorial I will show you how to create a dependent dropdown list in Laravel. So lets get started.
Below is a high level overview of the tutorial:
- Create models: We will create our models for the dependent dropdowns, such as
Country
,State
, andCity
- Create migration: Create a migration file to create the necessary tables in your database
- Create routes: Add routes to your
routes/web.php
file to handle the AJAX requests for loading the dependent dropdowns - Create controllers: Create controllers to handle the AJAX requests and return the data for the dependent dropdowns
- Create the views: Create Blade views for your form with the dependent dropdowns. In the example provided in, the form has three dropdowns for country, state, and city.
- Implement JavaScript: Use JavaScript and jQuery to handle the AJAX requests and update the dependent dropdowns based on the selected value in the top-level dropdown
Here’s a brief example of how to create a country, state, and city dynamic dependent dropdown in Laravel:
1. Create the necessary models:
As we are working with three entities, there are Country, City and State. You can run following commands to create the model files.
php artisan make:model Country -m php artisan make:model State -m php artisan make:model City -m
Now we will write necessary logic for these newly created models. Here we are creating Country model, where our fillable property is country “name”. And this Country model has many State class that is also mapped in this model.
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Country extends Model { protected $fillable = ['name']; public function states() { return $this->hasMany(State::class); } }
Now our next model is State model where fillable property is name and country_id as this belongs to a Country model, so we have to keep that mapping. And also, State has many cities, that is also mapped in this model.
namespace App\Models; use Illuminate\Database\Eloquent\Model; class State extends Model { protected $fillable = ['name', 'country_id']; public function country() { return $this->belongsTo(Country::class); } public function cities() { return $this->hasMany(City::class); } }
Finally, our next model is City model where fillable property is name and state_id as this belongs to a State model, so we have to keep that mapping. And also, a city must belongs to a State, that is also mapped in this model.
namespace App\Models; use Illuminate\Database\Eloquent\Model; class City extends Model { protected $fillable = ['name', 'state_id']; public function state() { return $this->belongsTo(State::class); } }
Our Model logic and relationship between models are done. Now we will proceed to our migrations files.
2. Create the migration:
Run below commands to create the migrations files.
php artisan make:migration create_countries_table --create=countries php artisan make:migration create_states_table --create=states php artisan make:migration create_cities_table --create=cities
Now we will update our migration files as per our need.
Migrations for Country model and associated table.
Schema::create('countries', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); });
Migrations for State model and associated table.
Schema::create('states', function (Blueprint $table) { $table->id(); $table->string('name'); $table->foreignId('country_id')->constrained()->onDelete('cascade'); $table->timestamps(); });
Migrations for City model and associated table.
Schema::create('cities', function (Blueprint $table) { $table->id(); $table->string('name'); $table->foreignId('state_id')->constrained()->onDelete('cascade'); $table->timestamps(); });
Now run this command to run the migrations.
php artisan migrate
Done for now. Let’s focus on the controllers now.
3. Create the routes:
These are our routes for the dependent dropdown list.
// routes/web.php Route::get('/get-states/{country_id}', 'DropdownController@getStates'); Route::get('/get-cities/{state_id}', 'DropdownController@getCities');
4. Create the controllers:
For simplicity, we will write all of our logics in DropDownController. To create this controller write below command and add the logics from below code box:
php artisan make:controller DropdownController
// DropdownController.php use App\Models\Country; use App\Models\State; use App\Models\City; public function getStates($country_id) { $states = State::where('country_id', $country_id)->get(); return response()->json($states); } public function getCities($state_id) { $cities = City::where('state_id', $state_id)->get(); return response()->json($cities); }
Here you can see, all the necessary models are imported, and we have similar logic for get country wise states and state wise cities. after pulling the data, we are returning JSON so that our frontend can consume that JSONs.
5. Create the views:
Below is our blade file, we can use it in any form.
<!-- views/your-form.blade.php --> <form> <div class="form-group mb-3"> <select id="country-dropdown" class="form-control"> <option value="">-- Select Country --</option> @foreach ($countries as $data) <option value="{{$data->id}}"> {{$data->name}} </option> @endforeach </select> </div> <div class="form-group mb-3"> <select id="state-dropdown" class="form-control"> <option value="">-- Select State --</option> </select> </div> <div class="form-group mb-3"> <select id="city-dropdown" class="form-control"> <option value="">-- Select City --</option> </select> </div> </form>
6. Implement JavaScript:
Now the final part, loading the data dynamically using JavaScript. Please make sure, jQuery library is loaded in your blade components. Here we are catching change events from country dropdown and state dropdown. taking these ids and pulling data from the DB based on the IDs. After that, dynamically generating HTML dropdown based on that. The code is pretty self explanatory.
// views/your-form.blade.php <script> $(document).ready(function() { $('#country-dropdown').on('change', function() { var country_id = $(this).val(); $.get('/get-states/' + country_id, function(data) { $('#state-dropdown').empty(); $('#state-dropdown').append('<option value="">-- Select State --</option>'); $.each(data, function(key, value) { $('#state-dropdown').append('<option value="' + key + '">' + value + '</option>'); }); }); }); $('#state-dropdown').on('change', function() { var state_id = $(this).val(); $.get('/get-cities/' + state_id, function(data) { $('#city-dropdown').empty(); $('#city-dropdown').append('<option value="">-- Select City --</option>'); $.each(data, function(key, value) { $('#city-dropdown').append('<option value="' + key + '">' + value + '</option>'); }); }); }); }); </script>
That’s it! You have successfully implemented a dependent dropdown list in Laravel. Now, selecting a country dynamically loads states, and selecting a state dynamically loads cities. Happy coding!
LaravelPlug.com is a simple tutorial blog where I share what is useful to the beginner users who are trying to learn Laravel, WordPress, Vue and much more.
If You have any query, suggestions, please contact us through below mail address:
info@laravelplug.com
Check Out More Resources:
Articles:
Website: https://laravelplug.com/
YouTube Channel: https://www.youtube.com/channel/UCnTxncHQcBSNs4RCuhWgF-A?sub_confirmation=1
WordPress Playlist: https://www.youtube.com/watch?v=8VvXzFAFwQU&list=PLVoVZqAh8dTLHZ51egvEU7dsOrRCSIMWx
Tools Playlist: https://www.youtube.com/watch?v=gTQoUn3BQkM&list=PLVoVZqAh8dTK-DWHBGWOEEvzvPQrgFne-
WordPress Tutorials: https://laravelplug.com/category/wordpress/
Laravel Tutorials: https://laravelplug.com/category/laravel/
PHP Tutorials: https://laravelplug.com/category/php/
SQL Tutorials: https://laravelplug.com/category/sql/
Various Tips: https://laravelplug.com/category/tips/
Useful Tools: https://laravelplug.com/category/tools/
Socials:
Twitter: https://twitter.com/LaravelPlug
Pinterest: https://www.pinterest.com/LaravelPlugCom/
Facebook: https://www.facebook.com/groups/1020759861842360
Mail: info@laravelplug.com
#Laravel #sql #mysql
That’s All. Feel free to knock me. Thanks.