Laravel Dependent Dropdown Tutorial With Example

Hello developers, Under this example, I will show you how to do Laravel Dependent Dropdown Tutorial With Example. We will get the second drop down item based on the first selected drop-down. When we select the first dropdown’s item, it will fire an AJAX request to the laravel server and in return, we get a response and we need to append that response to the second dropdown. So it is called dependent dropdown. You can find more about http request here.

Laravel Dependent Dropdown Tutorial With Example

We are going to Configure Laravel Project.

#1: Download Laravel Project

Establish  Laravel Project by the typing following command.

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

#2: Configure SQL Database

Now we can setup database credentials.

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

#3: Build Migration File

Here we will create two tables like country and state. First, create a country table so type following command in terminal.

php artisan make:migration create_countries_table --create=countries

It will create a create_countries_table.php  migration file.

//create_countries_table.php

public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

Here we add manually data in a database create_countries_table you can see below screenshot.

dependent dropdown using jquery ajax in laravel tutorial

Next, create a state table so type following command in terminal.

php artisan make:migration create_states_table --create=states

It will create a create_states_table.php  migration file.

//create_states_table

public function up()
    {
        Schema::create('states', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('countries_id');
            $table->string('name');
            $table->timestamps();
        });
    }

Here we add manually data in a database create_states_table you can see below screenshot.

dependent dropdown using jquery ajax in laravel example

#4: Create one controller

php artisan make:controller DataController

It will build a controller file called DataController.php.

Add following code into DataController.php file.

//DataController.php

use DB;

public function getCountries()
    {
        $countries = DB::table('countries')->pluck("name","id");
        return view('dropdown',compact('countries'));
    }

Here we create a method called getCountries(). This method returns all countries which we have included in the table. So pass countries to view file.

#5: Create a View File.

Create a file in resources/views/dropdown.blade.php and put this following code in it.

<!-- dropdown.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Dependent Dropdown  Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
  </head>
  <body>
    <div class="container">
    <h2>Laravel Dependent Dropdown  Tutorial With Example</h2>
            <div class="form-group">
                <label for="country">Select Country:</label>
                <select name="country" class="form-control" style="width:250px">
                    <option value="">--- Select Country ---</option>
                    @foreach ($countries as $key => $value)
                    <option value="{{ $key }}">{{ $value }}</option>
                    @endforeach
                </select>
            </div>
            <div class="form-group">
                <label for="state">Select State:</label>
                <select name="state" class="form-control"style="width:250px">
                <option>--State--</option>
                </select>
            </div>
      </div>
  </body>
</html>

#6: Define Route

We register all route in a web.php file.

//web.php

Route::get('dropdownlist','DataController@getCountries');
Route::get('dropdownlist/getstates/{id}','DataController@getStates');

You can see the screenshot when you change the country state doesn’t change because still we have not added the jQuery so next step will add jQuery code in the dropdown.blade.php file so let’s add.

laravel dependent dropdown ajax example

#7: Add jQuery Code

<!-- dropdown.blade.php -->

<script type="text/javascript">
    jQuery(document).ready(function ()
    {
            jQuery('select[name="country"]').on('change',function(){
               var countryID = jQuery(this).val();
               if(countryID)
               {
                  jQuery.ajax({
                     url : 'dropdownlist/getstates/' +countryID,
                     type : "GET",
                     dataType : "json",
                     success:function(data)
                     {
                        console.log(data);
                        jQuery('select[name="state"]').empty();
                        jQuery.each(data, function(key,value){
                           $('select[name="state"]').append('<option value="'+ key +'">'+ value +'</option>');
                        });
                     }
                  });
               }
               else
               {
                  $('select[name="state"]').empty();
               }
            });
    });
    </script>

Final code of dropdown.blade.php looks like below code.

<!-- dropdown.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Dependent Dropdown  Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
  </head>
  <body>
    <div class="container">
    <h2>Laravel Dependent Dropdown  Tutorial With Example</h2>
            <div class="form-group">
                <label for="country">Select Country:</label>
                <select name="country" class="form-control" style="width:250px">
                    <option value="">--- Select Country ---</option>
                    @foreach ($countries as $key => $value)
                    <option value="{{ $key }}">{{ $value }}</option>
                    @endforeach
                </select>
            </div>
            <div class="form-group">
                <label for="state">Select State:</label>
                <select name="state" class="form-control"style="width:250px">
                <option>--State--</option>
                </select>
            </div>
      </div>
    <script type="text/javascript">
    jQuery(document).ready(function ()
    {
            jQuery('select[name="country"]').on('change',function(){
               var countryID = jQuery(this).val();
               if(countryID)
               {
                  jQuery.ajax({
                     url : 'dropdownlist/getstates/' +countryID,
                     type : "GET",
                     dataType : "json",
                     success:function(data)
                     {
                        console.log(data);
                        jQuery('select[name="state"]').empty();
                        jQuery.each(data, function(key,value){
                           $('select[name="state"]').append('<option value="'+ key +'">'+ value +'</option>');
                        });
                     }
                  });
               }
               else
               {
                  $('select[name="state"]').empty();
               }
            });
    });
    </script>
  </body>
</html>

Add following code into DataController.php file.

//DataController.php


public function getStates($id) 
{        
        $states = DB::table("states")->where("countries_id",$id)->pluck("name","id");
        return json_encode($states);
}

Final Code of DataController.php looks like below code.

//DataController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class DataController extends Controller
{
    public function getCountries()
    {
        $countries = DB::table('countries')->pluck("name","id");
        return view('dropdown',compact('countries'));
    }

    public function getStates($id) 
    {
        $states = DB::table("states")->where("countries_id",$id)->pluck("name","id");
        return json_encode($states);
    }
}

laravel dependent dropdown ajax tutorial

At last, our Laravel Dependent Dropdown Tutorial With Example is over.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.