175 views
asked in Laravel by

Laravel Dependent AJAX Dropdown Country State City from MySQL Database 

1 Answer

answered by

Laravel Dependent AJAX Dropdown Country State City from MySQL Database 

***********************************************************************************************

Step 1 : Create Project in Laravel

composer create-project --prefer-dist laravel/laravel Laravel-Dependent-AJAX-Dropdown-CountryStateCity 

Note: open folder Laravel-Dependent-AJAX-Dropdown-CountryStateCity any text editor like vscode, notepad++ etc.

Step 2 : Add Database Details in .env file

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=laraveldropdowncountrystatecity

DB_USERNAME=root

DB_PASSWORD=

Step 3 : Create Model and Run Migration

php artisan make:model Country

php artisan make:model State

php artisan make:model City

php artisan make:migration create_country_state_city_tables

Step 4 : 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('country_id');

            $table->string('country_name');

            $table->timestamps();

        });

        Schema::create('states', function (Blueprint $table) {

            $table->increments('state_id');

            $table->string('state_name');

            $table->integer('country_id');

            $table->timestamps();

        });

        Schema::create('cities', function (Blueprint $table) {

            $table->increments('city_id');

            $table->string('city_name');

            $table->integer('state_id');            

            $table->timestamps();

        });

    }

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::drop('countries');

        Schema::drop('states');

        Schema::drop('cities');

    }

}

Step 5 : Run Migration for creating database and tables.

php artisan migrate

Step 6 : Crate Controller

php artisan make:controller DropdownController

Step 7 : Write code in controller

<?php

namespace App\Http\Controllers;

 

use Illuminate\Http\Request;

use App\Models\{Country, State, City};

class DropdownController extends Controller

{

    public function index()

    {

        $data['countries'] = Country::get(["country_id","country_name"]);

        return view('index', $data);

    }

    public function getStates(Request $request)

    {

        $data['states'] = State::where("country_id",$request->country_id)->get(["state_id","state_name"]);

        return response()->json($data);

    }

    public function getCities(Request $request)

    {

        $data['cities'] = City::where("state_id",$request->state_id)->get(["city_id","city_name"]);

        return response()->json($data);

    }

}

Step 8 : Create Routes

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\DropdownController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

*/


Route::get('laravel-dropdown', [DropdownController::class, 'index']);

Route::post('get-states', [DropdownController::class, 'getStates']);

Route::post('get-cities', [DropdownController::class, 'getCities']);

Step 9 : Index Blade View Page

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel Dependent AJAX Dropdown Country State City</title>

    <!-- CSS only -->

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">

</head>

<body>

    <div class="container mt-4">

        <div class="row justify-content-center">

            <div class="col-md-8">

                <h2 class="mb-4"> Laravel Dependent AJAX Dropdown Country State City </h2>

                <form>

                    <div class="form-group mb-3">

                        <select  id="country-list" class="form-control">

                            <option value="">Select Country</option>

                            @foreach ($countries as $data)

                            <option value="{{$data->country_id}}">

                                {{$data->country_name}}

                            </option>

                            @endforeach

                        </select>

                    </div>

                    <div class="form-group mb-3">

                        <select id="states-list" class="form-control">

                            <option value="">Select State</option>

                        </select>

                    </div>

                    <div class="form-group">

                        <select id="cities-list" class="form-control">

                            <option value="">Select City</option>

                        </select>

                    </div>

                </form>

            </div>

        </div>

    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

    <script>

        $(document).ready(function () {

            $('#country-list').on('change', function () {

                var idCountry = this.value;

                $("#states-list").html('');

                $.ajax({

                    url: "{{url('get-states')}}",

                    type: "POST",

                    data: {

                        country_id: idCountry,

                        _token: '{{csrf_token()}}'

                    },

                    dataType: 'json',

                    success: function (result) {

                        $('#states-list').html('<option value="">Select State</option>');

                        $.each(result.states, function (key, value) {

                            $("#states-list").append('<option value="' + value

                                .state_id + '">' + value.state_name + '</option>');

                        });

                        $('#cities-list').html('<option value="">Select City</option>');

                    }

                });

            });

            $('#states-list').on('change', function () {

                var stateId = this.value;

                $("#cities-list").html('');

                $.ajax({

                    url: "{{url('get-cities')}}",

                    type: "POST",

                    data: {

                        state_id: stateId,

                        _token: '{{csrf_token()}}'

                    },

                    dataType: 'json',

                    success: function (stateresult) {

                        $('#cities-list').html('<option value="">Select City</option>');

                        $.each(stateresult.cities, function (key, value) {

                            $("#cities-list").append('<option value="' + value

                                .city_id + '">' + value.city_name + '</option>');

                        });

                    }

                });

            });

        });

    </script>

</body>

</html>

Step 10 : Run below command for Test Laravel Dependent AJAX Dropdown

php artisan serve

Step 11 : access in Browser

http://127.0.0.1:8000/laravel-dropdown

For Video tutorial. Go to below youtube channel.

Subscribe and like for more videos:

https://www.youtube.com/@chiragstutorial

Don't forget to, Follow, Like, Share &, Comment

...