Laravel Dynamic Dependent Dropdown using Ajax Example

10-Apr-2023

.

Admin

Laravel Dynamic Dependent Dropdown using Ajax Example

Hello Friends,

In this tutorial, I will show you a laravel dynamic-dependent dropdown using an ajax example. if you have a question about the laravel dynamic dependent dropdown using ajax then I will give a simple example with a solution. This tutorial will give you a simple example of the laravel ajax dependent dropdown. this example will help you with the laravel country state city dropdown. Here, Creating a basic example of a laravel dependent dropdown example.

In this example, we will create a country, state, and city dynamic-dependent dropdown in the laravel app. we will create a simple form with three dropdowns. When you select country then the state will populate in the next dropdown and when you select the state then the city will populate based on state. it's step-by-step and a simple example. so let's follow the below step to do this example.

You can use this example with laravel 6, laravel 7, laravel 8, and laravel 9 versions.

Step 1: Install Laravel


first of all we need to get a fresh Laravel version application using the bellow command, So open your terminal OR command prompt and run the bellow command:

composer create-project laravel/laravel example-app

Step 2: Create Migration for Table

In this step, we will create the migration for countries, states, and cities table. So let's run the below command to create tables.

php artisan make:migration create_countries_states_cities_tables

Next, simple update below code to migration file.

database/migrations/create_countries_states_cities_tables.php

<?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()

{

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()

{

Schema::dropIfExists('countries');

Schema::dropIfExists('states');

Schema::dropIfExists('cities');

}

};

Then run created new migration with below command:

php artisan migrate

Step 3: Create Models

In this step, we will create three models for tables Country.php, State.php, and City.php model file.

so, let's run the below command to create the file and update the following code:

php artisan make:model Country

You have to update your model file as below:

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;

/**

* Write code on Method

*

* @return response()

*/

protected $fillable = [

'name'

];

}

php artisan make:model State

You have to update your model file as below:

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;

/**

* Write code on Method

*

* @return response()

*/

protected $fillable = [

'name', 'country_id'

];

}

php artisan make:model City

You have to update your model file as below:

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;

/**

* Write code on Method

*

* @return response()

*/

protected $fillable = [

'name', 'state_id'

];

}

Step 4: Create Route

In this step, we will add three routes with GET and POST methods in the routes/web.php file. so let's add it.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\DropdownController;

/*

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

| 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('dropdown', [DropdownController::class, 'index']);

Route::post('api/fetch-states', [DropdownController::class, 'fetchState']);

Route::post('api/fetch-cities', [DropdownController::class, 'fetchCity']);

Step 5: Create Controller

In this step, we have to create new controller as DropdownController with index(), fetchState() and fetchCity() methods.

php artisan make:controller DropdownController

Now let's update follow code:

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;

class DropdownController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$data['countries'] = Country::get(["name", "id"]);

return view('dropdown', $data);

}

/**

* Write code on Method

*

* @return response()

*/

public function fetchState(Request $request)

{

$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)

{

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

->get(["name", "id"]);

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

}

}

Step 6: Create View File

In Last step, let's create dropdown.blade.php for display form and put following code:

resources/views/dropdown.blade.php

<!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 Dynamic Dependent Dropdown using Ajax Example - NiceSnippets.com</title>

<style type="text/css">

body{

background-color: #d2d2d2 !important;

}

.dropdown{

background-color: #fff;

}

</style>

<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-5 justify-content-center">

<div class="row">

<div class="col-md-12 dropdown rounded p-5 mt-5">

<div class="row">

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

<h4>Laravel Dynamic Dependent Dropdown using Ajax Example</h4>

</div>

<div class="col-md-3 mb-3 text-end">

<strong class="col-md-5 p-0 m-0 text-end" style="color: #008B8B">NiceSnippets.com</strong>

</div>

</div>

<form>

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

<label class="form-control-label" for="country">Country</label>

<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">

<label class="form-control-label" for="state">State</label>

<select id="state-dropdown" class="form-control">

</select>

</div>

<div class="form-group">

<label class="form-control-label" for="city">City</label>

<select id="city-dropdown" class="form-control">

</select>

</div>

</form>

</div>

</div>

</div>

</body>

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

<script>

$(document).ready(function () {

/*------------------------------------------

--------------------------------------------

Country Dropdown Change Event

--------------------------------------------

--------------------------------------------*/

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

var idCountry = this.value;

$("#state-dropdown").html('');

$.ajax({

url: "{{url('api/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 Change Event

--------------------------------------------

--------------------------------------------*/

$('#state-dropdown').on('change', function () {

var idState = this.value;

$("#city-dropdown").html('');

$.ajax({

url: "{{url('api/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>

</html>

Step 7: Create Seeder

In this step, we will create a "CountrySateCitySeeder" file to create dummy records. so let's create seeder and run it.

Create Seeder file using below command:

php artisan make:seeder CountrySateCitySeeder

let's update following code on seeder file:

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()

{

/*------------------------------------------

--------------------------------------------

US Country Data

--------------------------------------------

--------------------------------------------*/

$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']);

/*------------------------------------------

--------------------------------------------

India Country Data

--------------------------------------------

--------------------------------------------*/

$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']);

}

}

Next, run seeder with below command:

php artisan db:seed --class=CountrySateCitySeeder

Start Development Server

Start the development server. Use the PHP artisan serve command and start your server:

php artisan serve

Now you are ready to run our example so run the below command to quick run.

http://localhost:8000/dropdown

#Laravel