Country State City Dropdown using Ajax in Laravel

Country State City Dropdown using Ajax in Laravel

Laravel country state city dependent dropdown tutorial. Here, we will show you how to create dependent country state city dropdown using jQuery ajax in laravel.

This ajax country state city dropdown in laravel tutorial will guide you step by step on how to create ajax country state city dropdown in laravel with live demo.

This dependent country state city dropdown using jquery ajax in laravel app will look like in following picture:

country state city dropdown using ajax in laravel

Laravel Ajax Country State City Dropdown

Follow below given simple steps to create country state city dependent dropdown list in laravel using jQuery ajax and as well as we provide live demo:

  • Step 1: Install Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Country State City Migration and Model File
  • Step 4: Add Routes For Country State City
  • Step 5: Create Controller For Fetch Country State City
  • Step 6: Create Blade File For Show Dependent Country State City in Dropdown
  • Step 7: Run Development Server

Step 1: Install Laravel App

In this step, open a terminal and run the following command. This command will install or download laravel fresh application setup for create dependent country state city dropdown list in laravel with ajax and live demo:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Add Database Details

In this step, Navigate to your project root directory and open the “.env” file. Then add database details into .evn file, as follow:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

Step 3: Create Country State City Migration and Model File

In this step, create a migration and model file for the country state city in laravel app. So run the following commands on command prompt:

cd blog

php artisan make:model Country
php artisan make:model State
php artisan make:model City

php artisan make:migration create_country_state_city_tables

Next, Navigate to database/migrations directory and open create_country_state_city_tables.php. Then update the following code into create_country_state_city_tables.php file, as follow:

<?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('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');
    }
}

Then, run the following command on command prompt:

php artisan migrate

This command will create countries, states, cities tables in your database.

Step 4: Add Routes For Country State City

In this step, Navigate to the routes directory and open web.php file. Then add the following routes into web.php file, as follow:

Route::get('country-state-city','[email protected]');
Route::post('get-states-by-country','[email protected]tState');
Route::post('get-cities-by-state','[email protected]');

Step 5: Create Controller For Fetch Country State City

In this step, create one controller file name CountryStateCityController.php. So open your terminal and run the following command to create PostController file, as follow:

php artisan make:controller CountryStateCityController

Then, Navigate to app/http/controllers and open CountryStateCityController.php file. And update the following code into your CountryStateCityController.php file, as follow:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator,Redirect,Response;
use App\{Country,State,City};

class CountryStateCityController extends Controller
{

    public function index()
    {
        $data['countries'] = Country::get(["name","id"]);
        return view('country-state-city',$data);
    }
    public function getState(Request $request)
    {
        $data['states'] = State::where("country_id",$request->country_id)
                    ->get(["name","id"]);
        return response()->json($data);
    }
    public function getCity(Request $request)
    {
        $data['cities'] = City::where("state_id",$request->state_id)
                    ->get(["name","id"]);
        return response()->json($data);
    }

}

Step 6: Create Blade File For Show Dependent Country State City in Dropdown

In this step, Navigate to resources/views directory And create 1 blade views that named country-state-city.blade.php the file inside this directory.

Then open country-state-city.blade.php file and update the following code into create.blade.php file, as follow:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="content">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel PHP Ajax Country State City Dropdown List - Tutsmake.COM</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h2 class="text-success">Laravel Country State City Dependent Dropdown List with Ajax - Tutsmake.COM</h2>
</div>
<div class="card-body">
<form>
<div class="form-group">
<label for="country">Country</label>
<select class="form-control" id="country-dropdown">
<option value="">Select Country</option>
@foreach ($countries as $country) 
<option value="{{$country->id}}">
{{$country->name}}
</option>
@endforeach
</select>
</div>
<div class="form-group">
<label for="state">State</label>
<select class="form-control" id="state-dropdown">
</select>
</div>                        
<div class="form-group">
<label for="city">City</label>
<select class="form-control" id="city-dropdown">
</select>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#country-dropdown').on('change', function() {
var country_id = this.value;
$("#state-dropdown").html('');
$.ajax({
url:"{{url('get-states-by-country')}}",
type: "POST",
data: {
country_id: country_id,
_token: '{{csrf_token()}}' 
},
dataType : 'json',
success: function(result){
$('#state-dropdown').html('<option value="">Select State</option>'); 
$.each(result.states,function(key,value){
$("#state-dropdown").append('<option value="'+value.id+'">'+value.name+'</option>');
});
$('#city-dropdown').html('<option value="">Select State First</option>'); 
}
});
});    
$('#state-dropdown').on('change', function() {
var state_id = this.value;
$("#city-dropdown").html('');
$.ajax({
url:"{{url('get-cities-by-state')}}",
type: "POST",
data: {
state_id: state_id,
_token: '{{csrf_token()}}' 
},
dataType : 'json',
success: function(result){
$('#city-dropdown').html('<option value="">Select City</option>'); 
$.each(result.cities,function(key,value){
$("#city-dropdown").append('<option value="'+value.id+'">'+value.name+'</option>');
});
}
});
});
});
</script>
</body>
</html>

Don’t forget to add country state city script code into your country-state-city.blade.php file, after the closing of body tag:

<script>
$(document).ready(function() {
$('#country-dropdown').on('change', function() {
var country_id = this.value;
$("#state-dropdown").html('');
$.ajax({
url:"{{url('get-states-by-country')}}",
type: "POST",
data: {
country_id: country_id,
_token: '{{csrf_token()}}' 
},
dataType : 'json',
success: function(result){
$.each(result.states,function(key,value){
$("#state-dropdown").append('<option value="'+value.id+'">'+value.name+'</option>');
});
$('#city-dropdown').html('<option value="">Select State First</option>'); 
}
});
});    
$('#state-dropdown').on('change', function() {
var state_id = this.value;
$("#city-dropdown").html('');
$.ajax({
url:"{{url('get-cities-by-state')}}",
type: "POST",
data: {
state_id: state_id,
_token: '{{csrf_token()}}' 
},
dataType : 'json',
success: function(result){
$.each(result.cities,function(key,value){
$("#city-dropdown").append('<option value="'+value.id+'">'+value.name+'</option>');
});
}
});
});
});
</script>

Step 7: Run Development Server

Finally, run the following php artisan command to start development server:

php artisan serve

After that open your browser and hit the following URL on it:

http://localhost:8000/country-state-city

Conclusion

Laravel dependent country state city dropdown. Here, you have learned how to create dependent dynamic country state city dropdown list in laravel with ajax and live demo.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Livewire, Codeigniter, Vue JS, Angular JS, React Js, WordPress, and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *