Hello Friends, today we are going on how to create a dynamic dependent dropdown in laravel 8 using jquery ajax(Laravel 8 Dynamic Dependent Dropdown using Jquery Ajax). so here we will give information about the ajax country state city dropdown.

when the user changes the dropdown value that time we are using the jquery change event then after we are sending requests using ajax. we are using different ajax request call in this example. like as get for state and city.

The dynamic dependent dropdown is commonly used in country-state-city and category-subcategory selection. Loading dynamic data into selection boxes without refreshing the page makes the web application easy to use.

Overview

Step 1: Install Laravel
Step 2: Setting Database Configuration
Step 3: Create a Table using migration
Step 4: Create Route
Step 5: Create a Model and Controller
Step 6: Create Blade Files
Step 7: Run The Application

Step 1: Install Laravel
We are going to install laravel 8, so first open the command prompt or terminal and go to xampp htdocs folder directory using the command prompt. after then run the below command.

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

Step 2: Setting Database Configuration

After the complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(laravel8_dynamic_dependent_dropdown)
DB_USERNAME=Enter_Your_Database_Username(root)
DB_PASSWORD=Enter_Your_Database_Password(root)

Step 3: Create a Table using migration

Now, We need to create a migration. so we will below command using create the images table migration.

php artisan make:migration create_country_state_city_tables

After complete migration. we need the below changes in the database/migrations/create_country_state_city_tablesfile.

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

Run the below command. after the changes above file.

php artisan migrate

Step 4: Create Route

Add the following route code in the “routes/web.php” file.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

use App\Http\Controllers\DropdownController;
 

Route::get('dropdown',[DropdownController::class, 'index']);
Route::get('getState',[DropdownController::class, 'getState'])->name('getState');
Route::get('getCity',[DropdownController::class, 'getCity'])->name('getCity');

Step 5: Create a Controller

Here below command helps to create the controller.

php artisan make:controller DropdownController

DropdownController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
class DropdownController extends Controller
{
	public function index()
	{
		$countries = DB::table("countries")->pluck("name","id");
		return view('dropdown',compact('countries'));
	}

	public function getState(Request $request)
	{
		$states = DB::table("states")
		->where("country_id",$request->country_id)
		->pluck("name","id");
		return response()->json($states);
	}

	public function getCity(Request $request)
	{
		$cities = DB::table("cities")
		->where("state_id",$request->state_id)
		->pluck("name","id");
		return response()->json($cities);
	}
}

Step 6: Create Blade Files

So finally, first we will create the dropdown.blade.php files in the “resources/views” directory.

dropdown.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Laravel 8 Dynamic Dependent Dropdown using Jquery Ajax - XpertPhp</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.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>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Laravel 8 Dynamic Dependent Dropdown using Jquery Ajax</h2>
    <div class="form-group">
      <label for="country">Country:</label>
	  <select id="country" name="category_id" class="form-control">
        <option value="" selected disabled>Select Country</option>
         @foreach($countries as $key => $country)
         <option value="{{$key}}"> {{$country}}</option>
         @endforeach
         </select>
    </div>
    <div class="form-group">
      <label for="state">State:</label>
      <select name="state" id="state" class="form-control"></select>
    </div>
	<div class="form-group">
      <label for="city">City:</label>
      <select name="city" id="city" class="form-control"></select>
    </div>
</div>
<script type=text/javascript>
  $('#country').change(function(){
  var countryID = $(this).val();  
  if(countryID){
    $.ajax({
      type:"GET",
      url:"{{url('getState')}}?country_id="+countryID,
      success:function(res){        
      if(res){
        $("#state").empty();
        $("#state").append('<option>Select State</option>');
        $.each(res,function(key,value){
          $("#state").append('<option value="'+key+'">'+value+'</option>');
        });
      
      }else{
        $("#state").empty();
      }
      }
    });
  }else{
    $("#state").empty();
    $("#city").empty();
  }   
  });
  $('#state').on('change',function(){
  var stateID = $(this).val();  
  if(stateID){
    $.ajax({
      type:"GET",
      url:"{{url('getCity')}}?state_id="+stateID,
      success:function(res){        
      if(res){
        $("#city").empty();
		$("#city").append('<option>Select City</option>');
        $.each(res,function(key,value){
          $("#city").append('<option value="'+key+'">'+value+'</option>');
        });
      
      }else{
        $("#city").empty();
      }
      }
    });
  }else{
    $("#city").empty();
  }
    
  });
</script>
</body>
</html>

Step 7: Run The Application

We can start the server and run this application using the below command.

php artisan serve

Now we will run our example using the below Url in the browser.

http://127.0.0.1:8000/dropdown

Download