Dynamic Dependent Dropdown With Ajax Using Laravel

admin_img Posted By Bajarangi soft , Posted On 15-01-2021

When we are working with the different application where we need to define a dependent dropdown such as classified application then there is a need to define the dependent dropdown such as category, sub-category, and sub-sub-category. we know that every category have many sub-categories and every sub-category have many sub-sub-category.

How to make simple dependent dropdown using ajax in laravel

Step 1:You have to create Three tables like State and city.

1
India
2
USA
3
Canada
4
UK
 
1
1
Gujarat
2
1
Maharashtra  
3
2
Toronto
 
1
1
Bangalore
2
1
Surat
3
2
Mumbai
4
2
Pune

Step 2: Make a new Project using below command ,You can run it in command prompt.
 
composer create-project --prefer-dist laravel/laravel datatable

Step 3: Write a database name in .env file for database connection.

Step 4:Run the command for database migration.

 
php aritsan make:auth
php aritsan migrate
 
Step 5:Create a blade file like dropdown.blade.php 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 $val)
                   <option value="{{$val->country_id}}">{{$val->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>

 


Step 5: Make a script for get data in on change event.
 
<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>

 


Step 6: Create Controller for dropdownController using below Command.
 
php artisan make:controller dropdownController

Step 7 :Make a function for getting data in Controller file.

 

public function dropdown()
    {
        $country = \Illuminate\Support\Facades\Country::get();
        return view('dropdown')->with('country', $country);
    }
public function getstate($id)
{
    $state = State::where("country_id",$id)
        ->pluck("state_name",$id);
    return response()->json($state);
}

public function getcity($id)
{
    $cities = City::where("state_id",$id)
        ->pluck("city_name","id");
    return response()->json($cities);
}

Step 8: Make a route between controller and blade file
 
Route::get('dropdown', 'dropdownController@dropdown');
Route::get('country/{id}','dropdownController@getstate');
Route::get('state/{id}','dropdownController@getcity');

Related Post