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','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")->select("id","name");
            return view('index',compact('countries'));
        }

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

        public function getCityList(Request $request)
        {
            $cities = DB::table("cities")->where("id","name");
            ->where("state_id",$request->state_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 href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">  
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></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 => $country)
         <option value="{{$country->id}}"> {{$country->name}}</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="'+value.id+'">'+value.name+'</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="'+value.id+'">'+value.name+'</option>');
        });
      
      }else{
        $("#city").empty();
      }
      }
    });
  }else{
    $("#city").empty();
  }
    
  });
</script>
</body>
</html>

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

Comments are closed.