Laravel 10 Dynamic Dependent Dropdown Using Ajax Example

Reading Time: 8 minutes
462 Views

Dynamic dependent dropdowns, also known as chained or cascading dropdowns, are a prominent feature in web applications that allow users to select options in one dropdown based on what they select in another. Using Ajax, you can easily create this functionality in Laravel 10. In this example tutorial, we’ll show you how to make dynamic dependent dropdowns in Laravel 10 using Ajax.

When dealing with connected data, such as categories and subcategories, countries and states, or any other hierarchical option, dynamic dependent dropdowns are especially handy.

Example of Country, State and City dropdown:

Read More: How To Create RSS Feed in Laravel 10 Example Tutorial

In this article, we’ll show you how to set up and populate these dropdowns dynamically without having to refresh the page.

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Setup Table Migration

Open project into terminal and run this command,

$ php artisan make:migration create_country_state_city_tables

It will create a file i.e 2023_09_06_054609_create_country_state_city_tables.php at /database/migrations folder.

Read More: Laravel 10 Submit Livewire Form Data Tutorial

Open Migration file and write this complete code into it.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->id('id');
            $table->string('name');
            $table->string('sortname');
            $table->string('phonecode');
        });
        Schema::create('states', function (Blueprint $table) {
            $table->id('id');
            $table->string('name');
            $table->integer('country_id');
        });
        Schema::create('cities', function (Blueprint $table) {
            $table->id('id');
            $table->string('name');
            $table->integer('state_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('countries');
        Schema::dropIfExists('states');
        Schema::dropIfExists('cities');
    }
};

Next,

Run Migration

We need to create tables inside database.

$ php artisan migrate

This command will create tables – countries, states & cities inside database.

Create Test Data (DB Tables)

Here, you will find a link. Download file from it. Copy the SQL code of data and run into Sql Tab of PhpMyAdmin,

You will see something like this after test data insertion.

countries” table

states” table

cities” table

Now,

Create Data Controller

You need to create a controller file.

$ php artisan make:controller DropdownController

It will create a file DropdownController.php inside /app/Http/Controllers folder.

Open file and write this complete code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\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);
    }
}

Create Blade Layout File

Go to /resources/views folder and create a file with name dropdown.blade.php,

Read More: Laravel 10 Auth with Livewire Jetstream Tutorial

Open file and write this complete code into it.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Laravel 10 Dynamic Dependent Dropdown using jQuery Ajax</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>

    <div class="container">
        <h3>Laravel 10 Dynamic Dependent Dropdown using jQuery Ajax</h3>
        <div class="panel panel-primary">
            <div class="panel-heading">Laravel 10 Dynamic Dependent Dropdown using jQuery Ajax</div>
            <div class="panel-body">
                <div class="form-group">
                    <label for="country">Country:</label>
                    <select id="country" name="country" 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>
        </div>
    </div>
    <script>
    // when country dropdown changes
    $('#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();
        }
    });

    // when state dropdown changes
    $('#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>

Add Route

Open web.php from /routes folder and add these route into it.

//...
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');

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/dropdown

Step #1

When select Country,

Next,

Read More: Laravel 10 API Testing Tool Package Tutorial

Step #2

When select State,

Finally, you will see all values as

We hope this article helped you to learn about Laravel 10 Dynamic Dependent Dropdown Using Ajax Example Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.