How to Show Dynamic Dependent Dropdown in Laravel?

Here in this tutorial, I am talking about how to create a simple laravel dependent dropdown by using jquery ajax. Now here by this simple example we can understand how to work with dependent dropdown in laravel even if any one is beginner. We are able to create the dynamic dependent dropdown in any version laravel 6, laravel 7 and laravel 8 application.

Sometimes we may need to make the dependent dropdown as like when we select state at that time load the city list in drop down list should be change. Here i mean that related to selected state. Now in this example i need two tables and there are listed in bellow:

1.state

2.cities

So, when any user change the state at that time, dynamically change city drop down box load from database. We can easily implement this example in our application by follow bellow few step.

Step 1: Create Tables

Now In first step we need to create to model with migration one for state and another one cities tables by using Laravel php artisan command, so first fire bellow command:

php artisan make:model State -m

And

php artisan make:model City -m

After this command we will find one file in following path database/migrations and we need to put bellow code in our migration file for create the tables.

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class CreateStateTables extends Migration
{
   public function up()
   {
       Schema::create('states', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

   }
   public function down()
   {
       Schema::drop('states');
      
   }
}
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class CreateCityTables extends Migration
{
   public function up()
   {
      

        Schema::create('cities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('state_id');
            $table->string('name');
            $table->timestamps();
        });
   }
   public function down()
   {
       Schema::drop('cities');
   }
}

After this migration, you need to run the migration by using artisan command as like as bellow:

php artisan migrate

Now, in our database, you will got two tables one is “state” and another one is “cities”.

Step 2: Add Route

So in this is step we need to create new route two, one for the layout and second one for ajax request. So need to open our routes/web.php file and add the following route.

Route::get('myform',array('as'=>'myform','uses'=>'HomeController@myform'));
Route::get('myform/ajax/{id}',array('as'=>'myform.ajax','uses'=>'HomeController@myformAjax'));
Step 3: Add Controller Method

Ok, now we need to create new controller as name HomeController if you haven’t create before in this path app/Http/Controllers/HomeController.php. This controller will manage all the layout and also dynamic ajax data, so need to put the bellow content in controller file :

app/Http/Controllers/HomeController.php

namespace App\Http\Controllers;


use App\Http\Requests;
use Illuminate\Http\Request;
use DB;


class HomeController extends Controller
{


    /**
     * Show the application layout
     *
     * @return \Illuminate\Http\Response
     */
    public function myform()
    {
        $states = DB::table("demo_state")->lists("name","id");
        return view('myform',compact('states'));
    }


    /**
     * Get Ajax Request and restun Data
     *
     * @return \Illuminate\Http\Response
     */
    public function myformAjax($id)
    {
        $cities = DB::table("demo_cities")
                    ->where("state_id",$id)
                    ->lists("name","id");
        return json_encode($cities);
    }


}
Step 4: Add Blade File

We are now in Last step, we need to create myform.blade.php file in our resources directory on that way we can write the jquery code and layout. So, just create a new blade file from the following path and then put the bellow code:

resources/view/myform.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Dependent Dropdown Example with demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"  referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.1/js/bootstrap.min.js">
</head>
<body>


<div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">Select State and get bellow Related City</div>
      <div class="panel-body">
            <div class="form-group">
                <label for="title">Select State:</label>
                <select name="state" class="form-control" style="width:350px">
                    <option value="">--- Select State ---</option>
                    @foreach ($states as $key => $value)
                        <option value="{{ $key }}">{{ $value }}</option>
                    @endforeach
                </select>
            </div>
            <div class="form-group">
                <label for="title">Select City:</label>
                <select name="city" class="form-control" style="width:350px">
                </select>
            </div>
      </div>
    </div>
</div>


<script type="text/javascript">
    $(document).ready(function() {
        $('select[name="state"]').on('change', function() {
            var stateID = $(this).val();
            if(stateID) {
                $.ajax({
                    url: '/myform/ajax/'+stateID,
                    type: "GET",
                    dataType: "json",
                    success:function(data) {

                        
                        $('select[name="city"]').empty();
                        $.each(data, function(key, value) {
                            $('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
                        });


                    }
                });
            }else{
                $('select[name="city"]').empty();
            }
        });
    });
</script>


</body>
</html>

Read Also: How to check request is Ajax or not in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.