Monday, June 27, 2016

Cascading / Dependent / Dynamic Dropdown list in Laravel using Ajax

laravel cascading dropdown


There is a situation where you want to populate your input select based on another input . For instance, in Category - Subcategory relationship where Category has many Subcategory. So in each Subcategory has its own Category . In your select input you don’t want to display all Categories to a Subcategory that has no relation to it.
What we want is to repopulate the Category input select based on the Subcategory selection. So that when you select a Subcategory only those Categories under that Subcategory will be displayed.
Now let’s  start how can we do it with Ajax and Laravel. Just do follow the following steps:

1. Let's make  a view where we want to show that cascaded dropdown :
       <div class="form-group">
            <label for="">Category</label>
            <select class="form-control input-sm" required name="category_id" id="category" >
            <option>Select a Category</option>
            @foreach($category as $row)
            <option value="{{$row->id}}">{{$row->name}}</option>
            @endforeach
            </select>
        </div> 

         <div class="form-group">
            <label for="">Subcategory</label>
            <select class="form-control input-sm" required name="subcategory_id" id="category" >
            <option value=""></option>
            </select>
        </div> 

2 . Let's make Category and Sub Category table using artisan command :
php artisan make:migration create_categories_table

php artisan make:migration create_subcategories_table
It'll create two migration file in your database/migrations folder in your laravel application.
3. Now let's put foreign key in  subcategories table with category_id and run the following command:
php artisan migrate
It will make categories and subcategories table in your database.
4. Now let's put some demo data in your database. Let's say categories table  put Electronics &  Books and in subcategories table put  fridge, tv, mobile with categorie_id '1' and put TextBooks, Magazines with category_id '2'.
Fill the database with above procedure.
5. Let's make Route  which will load the cascaded/dependent value  : 
Route::get('ajax-category-subcategory',function(Request $request){
$cat_id = $request::input(['cat_id']);  
$subcategories=\App\Subcategory::where('category_id','=',$cat_id)->get();
return Response::json($subcategories);
});

6. Now we gonna write the ajax part in view page. Write the ajax part before closing body tag.
<script>
      $('#category').on('change',function(e){       
         $('#subcategory').find('option').remove().end();
           var cat_id = $('#category option:selected').attr('value');           
             var info=$.get("{{url('ajax-category-subcategory')}}",{cat_id:cat_id});
               info.done(function(data){     
                  $.each(data,function(index,subcatObj){
                     $('#subcategory').append('<option value="'+subcatObj.id+'">'+
                                subcatObj.name+'</option>');
                    });
        });            
        info.fail(function(){
          alert('ok');
        });
       });
    </script>

7. Now if you go the above mentioned route you'll load the view page and select any of the category.You'll see the subcategory list will loaded related the Category.
That's it for today. Hope you like the tutorial. Stay connected with my blog. See you in next session! 
Thank you.

Related Articles

1 comment: