Laravel dependent country state city dropdown ajax jquery

Laravel dependent country state city dropdown ajax jquery

Here, we will see Laravel dependent country state city dropdown using ajax and jquery. And we will create dynamic dependent country, state and city dropdown in laravel with the help of jquery and ajax.

In approx. all the applications where we need to take the user’s personal data we use this types of dynamic dependent dropdown. Here state is dependent on country and city is dependent on state.

So in this situation, first thing we need to select country and on the behalf of selected country we will get state’s data through ajax call and same thing for getting city data from selected state.

And there might be different situations where this feature can be use useful like we need to get data from category, subcategory and sub sub category and these are dependent on their parent category. 

So, without wasting our time, let’s start to create laravel dependent country state city dropdown step by step. And here i am assuming you have already installed laravel application in your system.

Step 1: Create Route

In the first step, we will create required  route for this feature example. Open routes/web.php file and add the route as given below.

Route::get('api/dependent-dropdown','HomeController@index');
Route::get('api/get-states','HomeController@getStates');
Route::get('api/get-cities','HomeController@getCities');

Step 2: Create Migration and Table

Since, we will get country, state and city data from database. So we will need to create tables to store that data. Now open your terminal or command prompt and run the following artian command as given below to create migration. We will a only a single migration file to create these three tables.

php artisan make:migration create_country_state_city_tables

Now open migration file created by the above above command placed in database/migrations directory and add table structure as mentioned below.

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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');
    }
}

After that using the command below, migrate this migration file to create countries, states and cities.

Step 3: Create Controller 

Now, in this step we will create HomeController as written in the routes. And add three methods to get country, state and city data and add some code to get these data from database. Now HomeController.php file will be llok like below.

app/Http/Controllers/HomeController.php

<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
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);
    }
}

Here, We have used DB query to get data from database. You can also create three models for these three tables.

Step 4: Create View/Blade Template

Now, we will need to create view file which is basically a blade template to show the data. So create index.blade.php file under resources/view directory and put the code like below.

resources/view/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel dependent country state city dropdown ajax jquery</title>
<meta http-equiv="content-type" content="text html; charset="utf-8""><link rel="stylesheet" href="http://www.phpzone.in/demo/css/bootstrap.min.css" /> 
<script src="http://www.phpzone.in/demo/js/jquery.min.js" ></script 
<script src="http://www.phpzone.in/demo/js/bootstrap.min.js" ></script> </head> <body> <div class="container"> <div class="panel panel-default"> <div class="panel-heading">Dependent country state city dropdown using ajax in PHP Laravel Framework</div> <div class="panel-body"> <div class="form-group"> <label for="title">Select Country:</label> {!! Form::select('country', ['' => 'Select'] +$countries,'',array('class'=>'form-control','id'=>'country','style'=>'width:350px;'));!!} </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('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>

After following all the step above, you have successfully created country, state and city dropdown in laravel. You can use this feature anywhere in the project.

You can also read a wonderful laravel column sorting and pagination tutorial by clicking on this link.