Thursday, December 26, 2024
Google search engine
HomeLanguagesLaravel 9 Country State City Dropdown using Ajax Example

Laravel 9 Country State City Dropdown using Ajax Example

Dependent country state city dropdown in Laravel 9 apps; In this tutorial, you will learn how to create a dynamic dependent country state city dropdown using ajax in Laravel 9 apps.

Laravel 9 Country State City Dropdown using Ajax Example

Let’s use the following steps to make dynamic dependent country state city dropdown in laravel 9 apps using ajax:

  • Step 1 – Install Laravel App
  • Step 2 – Connecting App to Database
  • 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
    • Implement Ajax Code for fetch State and City in Dropdown
  • Step 7 – Run Development Server
  • Step 8 – Start Laravel Country State City App

Step 1 – Install Laravel App

In this step, open a terminal and execute the following command to install or download laravel app for create dependent country state city dropdown list in laravel with ajax:

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

Step 2 – Connecting App to Database

In this step, Navigate to laravel app 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:

use App\Http\Controllers\CountryStateCityController;


Route::get('country-state-city', [CountryStateCityController::class, 'index']);
Route::post('get-states-by-country', [CountryStateCityController::class, 'getState']);
Route::post('get-cities-by-state', [CountryStateCityController::class, 'getCity']);

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\Models\{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, execute the php artisan command on terminal to start development server:

php artisan serve

Step 8 – Start Laravel Country State City App

Now, open your browser and hit the following URL on it:

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

Conclusion

Laravel 9 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.

Recommended Laravel Tutorials

RELATED ARTICLES

Most Popular

Recent Comments