Share this:

Hello folks, In this tutorial we are going to learn dependent dropdown using ajax in our laravel application. Dependent dropdown is a multi dropdown which is dependent to its top level dropdown. For example When we select Country its show all its States, and when we select State its show all its Cites.

So, In this tutorial we are learning dependent dropdown using ajax in laravel application. This tutorial help you with registration form where you want your users to fill there contact details like address with country, state, city. or you can use this dropdown to select products which has sub categories etc.

For this tutorial we are using the latest laravel 9 application. But this tutorial are going to work on any version of laravel 5, laravel 6, laravel 7, laravel 8.

Without further ado, we starts with our Dependent Dropdown using Ajax tutorial.

Also Read: Pass data from Controller to Blade View in Laravel

Steps for Dependent Dropdown using Ajax:

  • Step 1: Installing Laravel Application
  • Step 2: Creating Migration
  • Step 3: Creating Models
  • Step 4: Creating Routes
  • Step 5: Creating Controllers
  • Step 6: Creating View Blade File
  • Step 7: Creating Seeder
  • Step 8: Testing

Step 1: Installing Laravel Application

First, we are going to install a laravel 9 application. To install a laravel application run the following command in terminal

composer create-project laravel/laravel dependent-dropdown
cd dependent-dropdown
Installing Laravel 9 Application
Installing Laravel 9 Application

After installing the laravel application you also need to configure database. Open .env and update the database details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dropdown
DB_USERNAME=root
DB_PASSWORD=
Database Configuration
Database Configuration

Also Read: Working with TMDb API in Laravel 9

Step 2: Creating Migration

We are creating a countries, states and cities dropdown example. So, we are going to create three table for countries, states and cities.

So, Follow the bellow step to create a migration and update the code as shown bellow.

Run the following migration code in terminal to create a countries table.

php artisan make:migration create_countries_table

Now update the countries migration file as shown bellow. You can find countries migration file at database/migrations folder.

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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('countries');
    }
};
Creating Countries Migration File
Creating Countries Migration File

Run the following migration code in terminal to create a states table.

php artisan make:migration create_states_table

Now update the states migration file as shown bellow. You can find states migration file at database/migrations folder.

<?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('states', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('country_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('states');
    }
};
Creating States Migration File
Creating States Migration File

Likewise, we need to create a cities migration file by running the following code in terminal.

php artisan make:migration create_cities_table

Now update the cities migration file as shown bellow. You can find cities migration file at database/migrations folder.

<?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('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('cities');
    }
};
Creating Cities Migration File
Creating Cities Migration File

With all three migration for countries, states and cities has been created. We execute the migrate Artisan command by following command.

php artisan migrate 

The above command will create all the migration as you can see in the bellow image.

Running the Migrations
Running the Migrations

Also Read: Add Toast Notification in Laravel 9

Step 3: Creating Models

Now, we are going to create a models for country, state and city. Run the following command to create models for all three.

php artisan make:model Country
php artisan make:model State
php artisan make:model City
Creating Models for Country, State and City
Creating Models for Country, State and City

Now, Update the model as shown bellow.

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'
    ];
}

Also Read: Laravel 9 Shopping Cart Tutorial and Example

Step 4: Creating Routes

Now, we are going to create three routes with GET and POST methods. Open routes/web.php and update the following routes.

<?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('/', function () {
    return view('welcome');
});

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

Step 5: Creating Controllers

As you can see from above step we are added a controller in our routes with name DropdownController with “index”, “fetchState”, “fetchCity” methods. So we are going to create a new controller inside app/Http/Controllers with a name DropdownController.php and enter the following 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
{
    public function index()
    {
        $data['countries'] = Country::get(["name", "id"]);
        return view('dropdown', $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);
    }
}
Creating a Dropdown Controller with all methods
Creating a Dropdown Controller with all methods

Also Read: Laravel Add Watermark on Images

Step 6: Creating View Blade File

At last, we are going to create a view blade file for displaying the form. Create dropdown.blade.php file inside resources/views and enter the 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>Dependent Dropdown using Ajax Example Laravel - LaravelTuts.com</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-8">
                <div class="bg-dark text-white mb-4 text-center py-4">
                   <h4 >Dependent Dropdown using Ajax Example Laravel - LaravelTuts.com</h4>
                </div> 
                <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 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>
</body>
</html>
Creating a Blade View File for Dropdown form
Creating a Blade View File for Dropdown form

Also Read: How to Check Date is Today’s Date or not in Laravel Carbon?

Step 7: Creating Seeder

So, we need a data for countries, states and cities for testing our application. so we are going to add dummy records for this tutorial. we are going to create dummy records with seeder.

Create a seeder with the following command.

php artisan make:seeder CountrySateCitySeeder
Creating Seeder File for Dummy Records
Creating Seeder File for Dummy Records

Now update the 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']);
    }
}
Updating Seeder File with Demo Records
Updating Seeder File with Demo Records

Add the above seeder file to DatabaseSeeder.php to migrate the file.

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(CountrySateCitySeeder::class);
    }
}
Adding Dummy Seeder file to DatabaseSeeder
Adding Dummy Seeder file to DatabaseSeeder

Its time to run the migration with seeder.

php artisan migrate:fresh --seed
Running the Fresh Migration with Seeder
Running the Fresh Migration with Seeder

Or if you run the migration before then you can only run the seeder file

php artisan db:seed --class=CountrySateCitySeeder

Also Read: How to Get All env Variables in Laravel?

Step 8: Testing

Now everything is done. we can now test our Dependent Dropdown using Ajax Example Laravel application. Run the following command to start the laravel serve.

php artisan serve

and open any web browser and open the following URL.

http://127.0.0.1:8000/dropdown

Previews:

Preview for Dependent Dropdown using Ajax Example Laravel
Preview for Dependent Dropdown using Ajax Example Laravel
Preview for Dependent Dropdown using Ajax Example Laravel
Preview for Dependent Dropdown using Ajax Example Laravel

Conclusion

Today, We had learn Dependent Dropdown using Ajax Example Laravel. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Laravel Pagination Tutorial

Download

Share this:

Categorized in: