Laravel 10 AJAX Dependent Country State City Dropdown

Last Updated on by in Laravel

Laravel dependent country state city dropdown with AJAX tutorial. Throughout this comprehensive tutorial, you will determine how to create a dynamic dependent country state city dropdown taking jQuery AJAX’s help in the Laravel application.

Dependent dropdown’s are those UI elements whose value changes or updates based on one another’s dropdown’s value. In this tutorial, we will build a dependent dropdown using AJAX.

This will be a laravel dependent country city state dropdown example; however, as a developer, you might need a similar feature for some other scenarios.

For instance, you have to display sub-categories based on parent categories; hence this tutorial can also be a perfect reference for such scenarios.

This AJAX based dynamic country state city dropdown in laravel will showcase country state city, and the values will change based on the user’s selection.

Laravel 10 AJAX Dependent Country State City Dropdown Example

  • Step 1: Create Laravel Project
  • Step 2: Make Database Connection
  • Step 3: Create Model and Run Migration
  • Step 4: Create Controller
  • Step 5: Create Routes
  • Step 6: Create Blade View
  • Step 7: Test Country State City Dependent Dropdown

Create Laravel Application

Invoke the first step by installing a new laravel project; ignore this step if the app already installed:

composer create-project laravel/laravel laravel-dependent-dropdown-example --prefer-dist

Add Database Details

Then, open .env file and insert database name, username and password to make the database connection with the app:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Create Mode and Run Migration

Next, you need to create a country, state, and city model plus migration files:

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

php artisan make:migration create_country_state_city_tables

Subsequently, open database/migrations/create_country_state_city_tables.php file and update the following code:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCountryStateCityTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('sortname');
            $table->string('phonecode');
            $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();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('countries');
        Schema::drop('states');
        Schema::drop('cities');
    }
}

Next, you need to run the migration to migrate the countries, states, and cities:

php artisan migrate

After migrating the countries, state and cities tables in the database. Your next task is to populate countries, state and cities data into the respective tables.

Therefore, you can use the following URL to get the Countries, States and Cities SQL data and import directly into the tables to create the dependent dropdown list in laravel.

Prepare Controller

Next, you need to generate a new dropdown controller, execute the following command on the console screen:

php artisan make:controller DropdownController

Next, open and update app/Http/Controllers/DropdownController.php:

<?php

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;

use Validator;
use Response;
use Redirect;
use App\Models\{Country, State, City};

class DropdownController extends Controller
{
    public function index()
    {
        $data['countries'] = Country::get(["name", "id"]);
        return view('welcome', $data);
    }

    public function fetchState(Request $request)
    {
        $data['states'] = State::where("country_id",$request->country_id)->get(["name", "id"]);
        return response()->json($data);
    }

    public function fetchCity(Request $request)
    {
        $data['cities'] = City::where("state_id",$request->state_id)->get(["name", "id"]);
        return response()->json($data);
    }
}

Create Routes

Next, you need to declare three routes which will ensure making the POST and GET requests to handle the dependent dropdown data.

Thereupon, open routes/web.php and update the following file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DropdownController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/


Route::get('dependent-dropdown', [DropdownController::class, 'index']);
Route::post('api/fetch-states', [DropdownController::class, 'fetchState']);
Route::post('api/fetch-cities', [DropdownController::class, 'fetchCity']);

Create Blade View

This part explains how to create a dependent dropdown HTML structure and dynamically display the state and city names based on the country name selected by the user using the laravel routes.

Whereupon, open resources/views/welcome.blade.php file, likewise insert the following code within the file:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="content">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel Dependent AJAX Dropdown Tutorial</title>

    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-5">
                <h2 class="mb-4">Laravel AJAX Dependent Country State City Dropdown Example</h2>
                <form>
                    <div class="form-group mb-3">
                        <select  id="country-dd" class="form-control">
                            <option value="">Select Country</option>
                            @foreach ($countries as $data)
                            <option value="{{$data->id}}">
                                {{$data->name}}
                            </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group mb-3">
                        <select id="state-dd" class="form-control">
                        </select>
                    </div>
                    <div class="form-group">
                        <select id="city-dd" class="form-control">
                        </select>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#country-dd').on('change', function () {
                var idCountry = this.value;
                $("#state-dd").html('');
                $.ajax({
                    url: "{{url('api/fetch-states')}}",
                    type: "POST",
                    data: {
                        country_id: idCountry,
                        _token: '{{csrf_token()}}'
                    },
                    dataType: 'json',
                    success: function (result) {
                        $('#state-dd').html('<option value="">Select State</option>');
                        $.each(result.states, function (key, value) {
                            $("#state-dd").append('<option value="' + value
                                .id + '">' + value.name + '</option>');
                        });
                        $('#city-dd').html('<option value="">Select City</option>');
                    }
                });
            });
            $('#state-dd').on('change', function () {
                var idState = this.value;
                $("#city-dd").html('');
                $.ajax({
                    url: "{{url('api/fetch-cities')}}",
                    type: "POST",
                    data: {
                        state_id: idState,
                        _token: '{{csrf_token()}}'
                    },
                    dataType: 'json',
                    success: function (res) {
                        $('#city-dd').html('<option value="">Select City</option>');
                        $.each(res.cities, function (key, value) {
                            $("#city-dd").append('<option value="' + value
                                .id + '">' + value.name + '</option>');
                        });
                    }
                });
            });
        });

    </script>
</body>

</html>

Test Laravel Dependent Dropdown

Every procedure has been followed; now its time to start this app and test the dynamic dependent dropdown we built in laravel.

php artisan serve

Use the following URL to test the PHP AJAX country state city dropdown example:

http://127.0.0.1:8000/dependent-dropdown

Laravel Dependent Dropdown

Conclusion

Eventually, we have completed this Laravel dependent dropdown tutorial; in this tutorial, we created a feature to display state and city names based on the country name.

We fetched the country, city, and state names from the database and showed them in the dependent dropdown list using AJAX.