Ajax dynamic dependent country state city dropdown using jquery ajax in Laravel 5.6

Generic placeholder image
Brijpal Sharma
php sql laravel  

Date:-August 14th, 2018 , Posted On:- Web Development


In this blog post, we learn how to create an Ajax dynamic dependent country state city dropdown using jquery ajax in Laravel 5.6 step by step.

When we are working with the different application where we need to define a dependent dropdown such as classified application then there is a need to define the dependent dropdown such as category, sub-category, and sub-sub-category. we know that every category have many sub-categories and every sub-category have many sub-sub-category.

when a user selects a category, related sub-category dropdown list open this is work as in sub-category and sub-sub-category.

In this Blog post, we have three table :

  • countries table
  • states table
  • cities table

First, we will display all country name the first box and when we selecting any country from the country dropdown list then the related state will be shown in the second dropdown list and same when we select the state from state dropdown then the related city will be listed in the third dropdown.

Step:1 Create three tables

In the first step create table structure and so we are going to create migration file for the following table using php artisan command to create open your terminal and run following line of code.

php artisan make:migration create_country_state_city_tables

Once command runs successfully you can see a new file in the database->migration folder open and edit with code.

    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
        Schema::create('states', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('country_id');            
            $table->timestamps();
        });
        Schema::create('cities', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('state_id');            
            $table->timestamps();
        });
    }
    

    public function down()
    {
        Schema::drop('countries');
        Schema::drop('states');
        Schema::drop('cities');
    }

 

After saving, this file run migrate command 

php artisan migrate

Now you can see three table in your database, Add some data in your table.

Countries table.

codermen countries table

States Tables

codermen states table

Cities table

codermen cities table

Now we table three table countries, states and cities table with data.

 

Step:2 Define route 

Open a wep.php file and define the route for Ajax dynamic dependent country state city dropdown project.

Route::get('dropdownlist','DropdownController@index');
Route::get('get-state-list','DropdownController@getStateList');
Route::get('get-city-list','DropdownController@getCityList');

Step:3 Create a new controller DropdownController

we can see that in the above route using DropdownController three function index, getStatesList, and getCityList.

app/Http/Controllers/DropdownController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
class DropdownController extends Controller
{
    
        public function index()
        {
            $countries = DB::table("countries")->pluck("name","id");
            return view('index',compact('countries'));
        }

        public function getStateList(Request $request)
        {
            $states = DB::table("states")
            ->where("country_id",$request->country_id)
            ->pluck("name","id");
            return response()->json($states);
        }

        public function getCityList(Request $request)
        {
            $cities = DB::table("cities")
            ->where("state_id",$request->state_id)
            ->pluck("name","id");
            return response()->json($cities);
        }
}

Step:4 Create an index.blade.php file

 

<!DOCTYPE html>
<html>
<head>
    <title>Ajax dynamic dependent country state city dropdown using jquery ajax in Laravel 5.6</title>
    <link rel="stylesheet" href="http://www.codermen.com/css/bootstrap.min.css">    
    <script src="http://www.codermen.com/js/jquery.js"></script>
</head>
<body>
<div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">Ajax dynamic dependent country state city dropdown using jquery ajax in Laravel 5.6</div>
      <div class="panel-body">
            <div class="form-group">
                <select id="country" name="category_id" class="form-control" style="width:350px" >
                <option value="" selected disabled>Select</option>
                  @foreach($countries as $key => $country)
                  <option value="{{$key}}"> {{$country}}</option>
                  @endforeach
                  </select>
            </div>
            <div class="form-group">
                <label for="title">Select State:</label>
                <select name="state" id="state" class="form-control" style="width:350px">
                </select>
            </div>
         
            <div class="form-group">
                <label for="title">Select City:</label>
                <select name="city" id="city" class="form-control" style="width:350px">
                </select>
            </div>
      </div>
    </div>
</div>
<script type="text/javascript">
    $('#country').change(function(){
    var countryID = $(this).val();    
    if(countryID){
        $.ajax({
           type:"GET",
           url:"{{url('get-state-list')}}?country_id="+countryID,
           success:function(res){               
            if(res){
                $("#state").empty();
                $("#state").append('<option>Select</option>');
                $.each(res,function(key,value){
                    $("#state").append('<option value="'+key+'">'+value+'</option>');
                });
           
            }else{
               $("#state").empty();
            }
           }
        });
    }else{
        $("#state").empty();
        $("#city").empty();
    }      
   });
    $('#state').on('change',function(){
    var stateID = $(this).val();    
    if(stateID){
        $.ajax({
           type:"GET",
           url:"{{url('get-city-list')}}?state_id="+stateID,
           success:function(res){               
            if(res){
                $("#city").empty();
                $.each(res,function(key,value){
                    $("#city").append('<option value="'+key+'">'+value+'</option>');
                });
           
            }else{
               $("#city").empty();
            }
           }
        });
    }else{
        $("#city").empty();
    }
        
   });
</script>
</body>
</html>

Now You can run your application and see the result http://localhost:8000/dropdownlist 

 

 

 

 


About the author

user profile
Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

3 comments
Generic placeholder image
yaser alshikh
April 17th, 2019 - 10:04PM

how i can get data row more than key and value ?

Generic placeholder image
Russuo
May 05th, 2019 - 1:28PM

Thanks for the tutorial. How do we retrieve the fields value for editing? Thanks

Generic placeholder image
Russuo
May 09th, 2019 - 3:51PM

Hoe much do you charge for including the code for editing the dropdown values?

You must be logged in to post a comment.