Dependent Dropdown Using Ajax Laravel 11 Example

Hello, laravel web developers! In this, we'll see how to create a dependent dropdown using Ajax Laravel 11. Here, we'll see the country state city dropdown laravel 11 using Ajax. jQuery Ajax we'll select a country depend on the get state and depend on the get city in laravel 11.

Laravel 11 we'll create a dynamic AJAX dependent dropdown without page refresh.

Dependent Dropdown using AJAX Laravel 11

Laravel 11 Dependent Dropdown using AJAX

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following composer command.

composer create-project laravel/laravel example-app

 

Step 2: Create Migration

Then, we'll create migration for country, state, and city.

php artisan make:migration create_countries_states_cities_tables

Migration:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
  
        Schema::create('states', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('country_id');
            $table->timestamps();
        });
  
        Schema::create('cities', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('state_id'); 
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('countries');
        Schema::dropIfExists('states');
        Schema::dropIfExists('cities');
    }
};

Then, migrate the table into the database using the following command.

php artisan migrate

 

Step 3: Create Models

Next, we'll create a model for Country, State, and City.

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

app/Models/Country.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Country extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name'
    ];
}

app/Models/State.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class State extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'country_id'
    ];
}

app/Models/City.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
   
class City extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'state_id'
    ];
}

 

Step 4: Define Routes

Now, define the routes into the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\DropdownController;
    
Route::get('dropdown', [DropdownController::class, 'index']);
Route::post('fetch-states', [DropdownController::class, 'fetchState']);
Route::post('fetch-cities', [DropdownController::class, 'fetchCity']);

 

Step 5: Create Controller

Then, we'll create a DropdownController.php file and define the functions for State and City.

app/Http/Controllers/DropdownController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Country;
use App\Models\State;
use App\Models\City;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
  
class DropdownController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(): View
    {
        $data['countries'] = Country::get(["name", "id"]);
        return view('dropdown', $data);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function fetchState(Request $request): JsonResponse
    {
        $data['states'] = State::where("country_id", $request->country_id)
                                ->get(["name", "id"]);
  
        return response()->json($data);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function fetchCity(Request $request): JsonResponse
    {
        $data['cities'] = City::where("state_id", $request->state_id)
                                    ->get(["name", "id"]);
                                      
        return response()->json($data);
    }
}

 

Step 6: Create View File

Next, we'll create a blade file for view.

resources/views/dropdown.blade.php

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dependent Dropdown Using Ajax Laravel 11 Example - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <div class="container mt-4">
        <div class="card mt-5">
            <h3 class="card-header p-3">Laravel 11 AJAX Dependent Country State City Dropdown - Techsolutionstuff</h3>
            <div class="card-body">
                <form>
                    <div class="form-group mb-3">
                        <select id="country-dropdown" 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-dropdown" class="form-control">
                        </select>
                    </div>
                    <div class="form-group">
                        <select id="city-dropdown" class="form-control">
                        </select>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#country-dropdown').on('change', function () {
                var idCountry = this.value;
                $("#state-dropdown").html('');
                $.ajax({
                    url: "{{url('fetch-states')}}",
                    type: "POST",
                    data: {
                        country_id: idCountry,
                        _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 City --</option>');
                    }
                });
            });

            $('#state-dropdown').on('change', function () {
                var idState = this.value;
                $("#city-dropdown").html('');
                $.ajax({
                    url: "{{url('fetch-cities')}}",
                    type: "POST",
                    data: {
                        state_id: idState,
                        _token: '{{csrf_token()}}'
                    },
                    dataType: 'json',
                    success: function (res) {
                        $('#city-dropdown').html('<option value="">-- Select City --</option>');
                        $.each(res.cities, function (key, value) {
                            $("#city-dropdown").append('<option value="' + value
                                .id + '">' + value.name + '</option>');
                        });
                    }
                });
            });

        });
    </script>
</body>

</html>
 
Step 7: Create Seeder

Then, we'll create a seeder to generate dummy records. So, run the following command.

php artisan make:seeder CountrySateCitySeeder

database/seeders/CountrySateCitySeeder.php

<?php
  
namespace Database\Seeders;
  
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Country;
use App\Models\State;
use App\Models\City;
  
class CountrySateCitySeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run(): void
    {
        
        $country = Country::create(['name' => 'United State']);
        $state = State::create(['country_id' => $country->id, 'name' => 'Florida']);
        City::create(['state_id' => $state->id, 'name' => 'Miami']);
        City::create(['state_id' => $state->id, 'name' => 'Tampa']);
  
        $country = Country::create(['name' => 'India']);
        $state = State::create(['country_id' => $country->id, 'name' => 'Gujarat']);
        City::create(['state_id' => $state->id, 'name' => 'Rajkot']);
        City::create(['state_id' => $state->id, 'name' => 'Surat']);
  
    }
}

Now, run the seeder using the following command.

php artisan db:seed --class=CountrySateCitySeeder

 

Step 8: Run laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS