How To Create Dependent Drop down in Laravel

Laravel Dynamic Dependent Dropdown
••• How To Create Dependent Drop down in Laravel

In this tutorial, I am going to do How To Create Dependent Drop down in Laravel application using jquery ajax. In this simple example through we understand how to work dependent dropdown in laravel even if you beginner.

How To Create Dependent Drop down in Laravel


We sometimes require to make dependent dropdown like when state select at that time bellow city drop-down list should change, I mean related to the selected state. In this example, I have two tables and there are listed below:

1. state.php
2. cities.php

How to Create Laravel Dependant Drop down in Laravel

So, when user will change state at that time, dynamically change city drop down box from a database. you can implement this example in your application by following bellow few steps.

After complete bellow example, you will find layout as bellow:

So, when user will change state at that time, dynamically change city drop down box from the database. you can implement this example in your application by follow bellow few step.

After complete bellow example, you will find layout as below:

Step 1: Create Model


In the first step we have to create a migration for demo_state and demo_cities tables using Laravel 5 PHP artisan command, so first fire bellow command:

php artisan make:model Model\State 

php artisan make:model Model\City

After this command, you will find one file or Model in following path App/Http/Model/State.php and you have to put below code in your Model file for creating models.

<?php 
namespace App\Model; 
use Illuminate\Database\Eloquent\Model; 

class State extends Model 
{ 
//
}

And also find one more file or Model in following path App/Http/Model/City.php and you have to put below code in your Model file for creating models.

<?php 

namespace App\Model\Demo\dependent_dropdown; 
use Illuminate\Database\Eloquent\Model; 

class City extends Model 
{ 
//
}

Step 2: Create Controller


Now we can create Controller DependentDropdownController.

DependentDropdownController.php
<?php

namespace App\Http\Controllers\Demo\dependent_dropdown;

use App\Http\Controllers\Controller;
use App\Model\Demo\dependent_dropdown\City;
use App\Model\Demo\dependent_dropdown\State;
use Illuminate\Http\Request;

class DependentDropdownController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $states = State::all();
        return view('demo.dependent_dropdown.index',compact('states'));
    }

    public function destroy($id)
    {
        //
    }

    public function findCityWithStateID($id)
    {
        $city = City::where('state_id',$id)->get();
        return response()->json($city);
    }
}

Step 3: CreateRoute


Then, Im going to create the route for the function findCityWithStateID which is return the state with the state id

// this route can return the state with the state id
Route::get('findCityWithStateID/{id}','Demo\dependent_dropdown\DependentDropdownController@findCityWithStateID');

 

Step 4: Create View


Now I’m going to create the view for that Dependent Drop down in Laravel for the city respect to the state inside the resource/view/dropdown.

@extends('master.app')

@section('main-content')
<div class="col-md-8 col-md-offset-2">
	 <div class="panel panel-success">
      <div class="panel-heading">
      	Dynamic Deop down in Laravel City in State
      </div>
      <div class="panel-body">
	 	 <form action="{{ route('dynamic-dropdown-laravel.store') }}" method="post">
	 	 	{{ csrf_field() }}
			  <div class="row">
			  	<div class="col-md-6">
			  		<div class="form-group {{ ($errors->has('roll'))?'has-error':'' }}">
				    <label for="roll">State <span class="required">*</span></label>
				    <select name="state" class="form-control" id="state">
				    	<option value="">-- Select State --</option>
				    	@foreach ($states as $state)
				    		<option value="{{ $state->id }}">{{ ucfirst($state->state_name) }}</option>
				    	@endforeach
				    </select>
				 </div>
			  	</div>
			  	<div class="col-md-6">
			  		<div class="form-group {{ ($errors->has('name'))?'has-error':'' }}">
				    <label for="roll">City </label>
				    <select name="city" class="form-control" id="city">
				    </select>
				 </div>
			  	</div>
			  </div>
			</form> 
   	  </div>
    </div>
</div>
    
@endsection

Step 5: Create Ajax


Here is the Javascript code which is fetch the data fron the data base related to the state. its fetch the city of the state like when we select the state then automatically aapear city related that state.

@section('script')
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script type="text/javascript" src="{{ asset('assets/js/jquery-3.3.1.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('assets/js/bootstrap.min.js') }}"></script>
	<script>
         $(document).ready(function() {
        $('#state').on('change', function() {
            var stateID = $(this).val();
            if(stateID) {
                $.ajax({
                    url: '/findCityWithStateID/'+stateID,
                    type: "GET",
                    data : {"_token":"{{ csrf_token() }}"},
                    dataType: "json",
                    success:function(data) {
                        //console.log(data);
                      if(data){
                        $('#city').empty();
                        $('#city').focus;
                        $('#city').append('<option value="">-- Select City --</option>'); 
                        $.each(data, function(key, value){
                        $('select[name="city"]').append('<option value="'+ key +'">' + value.city_name+ '</option>');
                    });
                  }else{
                    $('#city').empty();
                  }
                  }
                });
            }else{
              $('#city').empty();
            }
        });
    });
    </script>

Now you should able to understand the Dependent Drop down in laravel. if you have a demo of this post go throygh the below link.

View Demo