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

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.

ajax in Laravel 5.6

When we are working with the different applications 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 has many sub-categories and every sub-category has 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

countries table

States Table

States Table

Cities table

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','[email protected]');
Route::get('get-state-list','[email protected]');
Route::get('get-city-list','[email protected]');

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="//www.codermen.com/css/bootstrap.min.css">  
  <script src=//www.codermen.com/js/jquery.js></script>
</head>
<body>
<div >
  <div >
   <div >Ajax dynamic dependent country state city dropdown using jquery ajax in Laravel 5.6</div>
   <div >
      <div >
        <select id="country" name=category_id  >
        <option value="" selected disabled>Select</option>
         @foreach($countries as $key => $country)
         <option value="{{$key}}"> {{$country}}</option>
         @endforeach
         </select>
      </div>
      <div >
        <label for="title">Select State:</label>
        <select name=state id="state" >
        </select>
      </div>
     
      <div >
        <label for="title">Select City:</label>
        <select name=city id="city" >
        </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 //localhost:8000/dropdownlist 

Leave a Comment