Dynamic Dependent Dropdown With Jquery Using Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

When we have select first select box then it will send Ajax request to Laravel code for fetch data for second select box. So this way child select box has been filled with data. This whole process has been done without refresh of web page because we have use Ajax with Laravel.

How to make simple dependent dropdown using ajax in laravel

Let's Learn
We have three different tables in database for that we are going to do dynamic dependent dropdown using Ajax.

Country table

country_id country_name
1 India
2 USA
3 Australia
4 UK

State table
state_id country_id state_name
1 1 Karnataka
2 1 Maharashtra  
3 2 California
4 2 Alaska
5 3 Tasmania
6 3 South Australia
7 4 Scotland
8 4 Wales

City table
city_id state_id city_name
1 1 Bangalore
2 1 Mysore
3 2 Mumbai
4 2 Pune


Install Laravel New Project for that run below code in command prompt.

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

1.Write database name in .env file in project to connect between web page and database.
2.Run a below commands.
php aritsan make:auth
php aritsan migrate


1.Create dropdown.blade.php file in resource/view folder.

<!DOCTYPE html>
<html>
<head>
    <title>How to Make Simple Dependent DropDown using Ajax in Laravel</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>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<br />
<h3 align="center">How to Make Simple Dependent DropDown using Ajax in Laravel</h3><br />
<br />
<br />
<div class="container well">
   <div class="col-md-6">
       <div class="form-group">
           <select name="country" id="country" class="form-control input-lg dynamic" data-dependent="state">
               <option value="">Select Country</option>
               @foreach($country as $cou)
                   <option value="{{$cou->country_id}}">{{$cou->country_name}}</option>
               @endforeach
           </select>
       </div>
       <br />
       <div class="form-group">
           <select name="state" id="state" class="form-control input-lg dynamic" data-dependent="city">
               <option value="">Select State</option>
           </select>
       </div>
       <br />
       <div class="form-group">
           <select name="city" id="city" class="form-control input-lg">
               <option value="">Select City</option>
           </select>
       </div>
       {{ csrf_field() }}
   </div>
    <br />
    <br />
</div>
</body>
</html>

2.Create script to get data when drop down changes.

<script>
    $(document).ready(function () {
        $('select[name="country"]').on('change', function () {
            var  country_id= $(this).val();
            var token = $("meta[name='_csrf']").attr("content");
            var html = "";
            if (country_id) {
                $.ajax({
                    url: '{{url('country')}}' + '/' + encodeURI(country_id),
                    type: "GET",
                    dataType: "json",
                    success: function (data) {
                        $('select[name="state"]').empty();
                        $('select[name="state"]').append('<option value="" selected disabled>Select state</option>');
                        $.each(data, function (key, value) {
                            $('select[name="state"]').append('<option value="' +
                                value.state_id + '">' + value.state_name + '</option>');
                        });
                    }
                });
            }
        });
    });
    $('select[name="state"]').on('change', function () {
        var state_id = $(this).val();
        var token = $("meta[name='_csrf']").attr("content");
        var html = "";
        if (state_id) {
            $.ajax({
                url: '{{url('state')}}' + '/' + encodeURI(state_id),
                type: "GET",
                dataType: "json",
                success: function (data) {
                    $('select[name="city"]').empty();
                    $('select[name="city"]').append('<option value="" selected disabled>Select city</option>');
                    $.each(data, function (key, value) {
                        $('select[name="city"]').append('<option value="' +
                            value. city_id + '">' + value.    city_name + '</option>');
                    });
                }
            });
        }
    });

</script>

3.Create controller to fetch data on webpage.

php artisan make:controller dropdownController


4.Implement code in dropdown controller.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use DB;

class dropdownController extends Controller
{
    public function dropdown()
    {
        $country = \Illuminate\Support\Facades\DB::table('countries')->get();
        return view('dropdown')->with('country', $country);

    }
 public function country($id)
    {
        $state=db::table("states")->where("country_id",$id)->get();
        return $state;

    } public function state($id)
    {
        $city=db::table("cities")->where("state_id",$id)->get();
        return $city;
    }
}
?>

5.Create link between controller and blade file using route.

Route::get('dropdown', 'AjaxUploadController@dropdown');
Route::get('country/{id}','AjaxUploadController@country');
Route::get('state/{id}','AjaxUploadController@state');

Related Post