onlinecode

Dependent country state city dropdown using jquery ajax in Laravel 5

Dependent country state city dropdown using jquery ajax in Laravel 5

In this post we will give you information about Dependent country state city dropdown using jquery ajax in Laravel 5. Hear we will give you detail about Dependent country state city dropdown using jquery ajax in Laravel 5And how to use it also give you demo for it if it is necessary.

Dependent country state city dropdown using jquery ajax in Laravel 5


In this tutorial, I am going to explain the dynamic dependent country state and city dropdown using jQuery Ajax in PHP Laravel and MySQL.

There are so many situation in the application where you will need to define dependent dropdown such as when you are working with e-commerce portal then there is need to define dependent dropdown for their category and sub-category because each category have many sub-categories so sub-category will be display on behalf of selected category.

In this post, i have three table :

  • countries table
  • states table
  • cities table

First i will display all country data in first select box and when i select any country from country dropdown then related state will be listed in second dropdown and same when i select state from state dropdown then related city will be listed in third dropdown.


Step 1: Create Tables

This is first step where i need to create table structure and for this i am going to create migration file for following table using Laravel php artisan command So open your terminal and run following line of code :

php artisan make:migration create_country_state_city_tables

Once command runs successfully then you will get a file in following path database/migrations and put following line of code in your migration file to create tables into your database.

  1. <?php
  2. use IlluminateDatabaseSchemaBlueprint;
  3. use IlluminateDatabaseMigrationsMigration;
  4. class CreateCountryStateCityTables extends Migration
  5. {
  6. public functionup()
  7. {
  8. Schema::create('countries',function(Blueprint $table){
  9. $table->increments('id');
  10. $table->string('sortname');
  11. $table->string('name');
  12. $table->timestamps();
  13. });
  14. Schema::create('states',function(Blueprint $table){
  15. $table->increments('id');
  16. $table->string('name');
  17. $table->integer('country_id');
  18. $table->timestamps();
  19. });
  20. Schema::create('cities',function(Blueprint $table){
  21. $table->increments('id');
  22. $table->string('name');
  23. $table->integer('state_id');
  24. $table->timestamps();
  25. });
  26. }
  27. public functiondown()
  28. {
  29. Schema::drop('countries');
  30. Schema::drop('states');
  31. Schema::drop('cities');
  32. }
  33. }
<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateCountryStateCityTables extends Migration
{
    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('sortname');
            $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');

    }
}

Now save this file and run migration using artisan command :


php artisan migrate

Now you will have three tables in your database that will use to get country state and their city on behalf of their relation.


countries table


states table


cities table

Ok, now we have countries, states and cities table.


Step 2: Define Route

In this step, i will define some route that handle url request.

  1. Route::get('api/dependent-dropdown','APIController@index');
  2. Route::get('api/get-state-list','APIController@getStateList');
  3. Route::get('api/get-city-list','APIController@getCityList');
Route::get('api/dependent-dropdown','APIController@index');
Route::get('api/get-state-list','APIController@getStateList');
Route::get('api/get-city-list','APIController@getCityList');


Step 3: Create APIControlle.php Filer

As you see in above routes there are a APIController having index, getStateList, getCityList. So in this step i will create a APIController.php with following methods.


app/Http/Controllers/APIController.php

  1. <?php
  2. namespace AppHttpControllers;
  3. use AppHttpRequests;
  4. use IlluminateHttpRequest;
  5. use DB;
  6. class APIController extends Controller
  7. {
  8. public functionindex()
  9. {
  10. $countries= DB::table("countries")->lists("name","id");
  11. returnview('index',compact('countries'));
  12. }
  13. public functiongetStateList(Request $request)
  14. {
  15. $states= DB::table("states")
  16. ->where("country_id",$request->country_id)
  17. ->lists("name","id");
  18. returnresponse()->json($states);
  19. }
  20. public functiongetCityList(Request $request)
  21. {
  22. $cities= DB::table("cities")
  23. ->where("state_id",$request->state_id)
  24. ->lists("name","id");
  25. returnresponse()->json($cities);
  26. }
  27. }
<?php
namespace AppHttpControllers;

use AppHttpRequests;
use IlluminateHttpRequest;
use DB;

class APIController extends Controller
{

    public function index()
    {
        $countries = DB::table("countries")->lists("name","id");
        return view('index',compact('countries'));
    }

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

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


Step 4: Create index.blade.php file

This is last step where i will create view index.blade.php file where all script will be written.


resources/view/index.blade.php

  1. <!DOCTYPEhtml>
  2. <html>
  3. <head>
  4. <title>Dependent country state city dropdown using ajax in PHP Laravel Framework</title>
  5. <linkrel="stylesheet"href="http://www.onlinecode.org/css/bootstrap.css">
  6. <scriptsrc="/https://onlinecode.org/js/jquery.js"></script>
  7. </head>
  8. <body>
  9. <divclass="container">
  10. <divclass="panel panel-default">
  11. <divclass="panel-heading">Dependent country state city dropdown using ajax in PHP Laravel Framework</div>
  12. <divclass="panel-body">
  13. <divclass="form-group">
  14. <labelfor="title">Select Country:</label>
  15. {!! Form::select('country', ['' => 'Select'] +$countries,'',array('class'=>'form-control','id'=>'country','style'=>'width:350px;'));!!}
  16. </div>
  17. <divclass="form-group">
  18. <labelfor="title">Select State:</label>
  19. <selectname="state"id="state"class="form-control"style="width:350px">
  20. </select>
  21. </div>
  22. <divclass="form-group">
  23. <labelfor="title">Select City:</label>
  24. <selectname="city"id="city"class="form-control"style="width:350px">
  25. </select>
  26. </div>
  27. </div>
  28. </div>
  29. </div>
  30. <scripttype="text/javascript">
  31. $('#country').change(function(){
  32. var countryID = $(this).val();
  33. if(countryID){
  34. $.ajax({
  35. type:"GET",
  36. url:"{{url('api/get-state-list')}}?country_id="+countryID,
  37. success:function(res){
  38. if(res){
  39. $("#state").empty();
  40. $("#state").append('<option>Select</option>');
  41. $.each(res,function(key,value){
  42. $("#state").append('<optionvalue="'+key+'">'+value+'</option>');
  43. });
  44. }else{
  45. $("#state").empty();
  46. }
  47. }
  48. });
  49. }else{
  50. $("#state").empty();
  51. $("#city").empty();
  52. }
  53. });
  54. $('#state').on('change',function(){
  55. var stateID = $(this).val();
  56. if(stateID){
  57. $.ajax({
  58. type:"GET",
  59. url:"{{url('api/get-city-list')}}?state_id="+stateID,
  60. success:function(res){
  61. if(res){
  62. $("#city").empty();
  63. $.each(res,function(key,value){
  64. $("#city").append('<optionvalue="'+key+'">'+value+'</option>');
  65. });
  66. }else{
  67. $("#city").empty();
  68. }
  69. }
  70. });
  71. }else{
  72. $("#city").empty();
  73. }
  74. });
  75. </script>
  76. </body>
  77. </html>
<!DOCTYPE html>
<html>
<head>
    <title>Dependent country state city dropdown using ajax in PHP Laravel Framework</title>
    <link rel="stylesheet" href="#">    
    <script src="https://onlinecode.org/js/jquery.js"></script>
</head>
<body>
<div >
    <div >
      <div >Dependent country state city dropdown using ajax in PHP Laravel Framework</div>
      <div >
            <div >
                <label for="title">Select Country:</label>
                {!! Form::select('country', ['' => 'Select'] +$countries,'',array('class'=>'form-control','id'=>'country','style'=>'width:350px;'));!!}
               
            </div>
            <div >
                <label for="title">Select State:</label>
                <select name="state" id="state"  style="width:350px">
                </select>
            </div>
         
            <div >
                <label for="title">Select City:</label>
                <select name="city" id="city"  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('api/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('api/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>

If you will get error like ‘HTML’ or ‘FORM’ class not found then click here to get solution :


Class form or html not found in Laravel 5

Show Demo

Label :

PHP

MySQL

Laravel PHP Framework

jQuery

How To

MVC

Apache

Web Development

JavaScript

Database

Hope this code and post will helped you for implement Dependent country state city dropdown using jquery ajax in Laravel 5. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Exit mobile version