0

This is output of image and which show all category and subcategory

What I want to achieve is to display all the categories and, when a category is clicked, its relative subcategory should be displayed.

The model view code

    <!-- Button to Open the Modal -->

      <div class="form-group col-md-8">
      <button type="button" class="form-control" data-toggle="modal" data-target="#myModal">
    Category  </button>

      <!-- The Modal -->
      <div class="modal" id="myModal">
    <div class="modal-dialog modal-lg" >
          <div class="modal-content">
          
            <!-- Modal Header -->
            <div class="modal-header">
              <h4 class="modal-title">Category</h4>
              <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            
            <!-- Modal body -->
            <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4" >
                                    <a href="#" name="category" id="category" >            
                                        @foreach($categories as $category)
                                        <option value="{{$category->id}}">{{$category->category}}</option>
                                        @endforeach
                                     </a>
                             
                        </div>
                          <div class="col-md-4 ">
                            <a href="#" name="subcategory" id="subcategory" >
                                @foreach($subcategories as $subcategory)
                                <option value="{{$subcategory->id}}">{{$subcategory->subcategory}}</option>
                                @endforeach
                             </a>
                                
                          </div>
                          <div class="col-md-4">
                            hhh
                          </div>
                  </div>
            </div>
          </div>
        </div>
      </div>

    </div>
    <script type="text/javascript">
      $(document).ready(function() {
       
                        $('#category').change(function(){
                var categoryID = $(this).val();
                if(categoryID){
                    $.ajax({
                        type:"GET",
                        url:"{{url('/api/getSubcategory/')}}/"+categoryID,

                        success:function(res){

                            if(res){
                                
                                data = JSON.parse(res)
                                $("#subcategory").empty();
                                $("#subcategory").append('<option>Select</option>');
                                $.each(data,function(key,value){
                                    $("#subcategory").append("<option value='"+key+"'>"+value+"</option>");
                                           
                                });

                            }else{
                                $("#subcategory").empty();
                            }
                        }
                    });
                }else{
                    $("#subcategory").empty();
                }
            });
                    });
</script>

The controller code:

public function create()
{
    $categories = Category::all();
    $subcategories = Subcategory::all();

    return view('post.create', compact('categories', 'subcategories'));
}

This is the route:

Route::get('/post/create', 'PostController@create')->name('post.create');

This is the API I created, but I don't know how to use it.

public function getSubcategory(Request $request)
{
    $id = $request->id;
    $subcategories = Subcategory::where('category_id',$id)
                         ->select('subcategory','id')
                         ->pluck('subcategory', 'id');
    {{ dd(json_decode($subcategories, true)); }}

    return json_encode($subcategories);
}

API route

Route::get('api/getSubcategory/{id}', 'PostController@getSubcategory');

How can I do this at runtime, when model is changed to a subcategory of its relative category.

Please help me. I am a beginner.

I want to this type of output output which i want

3 Answers3

0

As a beginner you can easily do something like this.

<div class="modal-body">
    <div class="row">
       <div class="col-md-4" >

        @foreach($categories as $category)

          <a href="#" name="category" id="category" >                            
              <option value="{{$category->id}}">{{$category->category}}</option>
          </a>

          <div class="col-md-4 ">

            @foreach($category->subcategory as $subcat)
                <a href="#" name="subcategory" class="subcategory" >
                    <option value="{{$subcat->id}}">{{$subcat->subcategory}}</option>                             
                </a>
             @endforeach
         </div>
        @endforeach

      </div>
  </div>

If you still want to load subcategories on click/hover events on category item, then you can do it using jquery library. This answer tells you about how to do something on mousehover event. Simply call your get subcategory route on that event via ajax, ($.ajax()) and append your result.

dilusha_dasanayaka
  • 1,401
  • 2
  • 17
  • 30
0

For your dynamic subcategory use below jquery Ajax function

<div class="modal-body">
  <div class="row">
        <div class="col-md-4" >
          <a href="#" name="category" id="category" >            
              @foreach($categories as $category)
              <option class="categoryList" value="{{$category->id}}">{{$category->category}}</option> <!-- add conman class for click event --> 
              @endforeach
           </a>
        </div>
        <div class="col-md-4 ">
          <a href="#" name="subcategory" id="subcategory" >
          </a>
        </div>
  </div>
</div>
<script type="text/javascript">
  $('.categoryList').on('click', function(){
  var cat_id = $(this).attr('value');
  var url = "localhost:8000/api/getSubcategory/"+cat_id;
  $.ajax({
      type: "GET",
      url: url,
      dataType: "JSON",
      success: function(res)
      {
        // amusing res = {"3":"home","4":"home duplex"}; 
        var html = "";
        $.each(res, function (key, value) {
             html += "<option value="+key+">"+value+"</option>";
        });
        $("#subcategory").html(html);
      }
  });
});
</script>

If you want to store your data in database then remove model and add below HTML put after your last form input.

<div class="col-md-4" >
  <select onchange="selectSubcategory(this)" name="category_id">            
      @foreach($categories as $category)
      <option value="{{$category->id}}">{{$category->category}}</option>
      @endforeach
  </select>
</div>
<div class="col-md-4 ">
  <select name="subcategory_id" id="subcategory_id">                                  
  </select>
</div>

below code for your dynamic subcategory

<script type="text/javascript">
  function selectSubcategory(obj){
  var cat_id = $(obj).val();
  var url = "localhost:8000/api/getSubcategory/"+cat_id;
  $.ajax({
      type: "GET",
      url: url,
      dataType: "JSON",
      success: function(res)
      {
        // amusing res = {"3":"home","4":"home duplex"}; 
        var html = "";
        $.each(res, function (key, value) {
             html += "<option value="+key+">"+value+"</option>";
        });
        $("#subcategory_id").html(html);
      }
  });
}
</script>

In your controller store method get category and subcategory like below

$request->category_id;
$request->subcategory_id;
0

@extends('layouts.app')

@section('content')
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>   
       <div class="modal-body">
  <div class="row">
        <div class="col-md-4" >
          <a href="#" name="category" id="category" >            
              @foreach($categories as $category)
              <option class="categoryList" value="{{$category->id}}">{{$category->category}}</option>
              @endforeach
           </a>
        </div>
        <div class="col-md-4 ">
          <a href="#" name="subcategory" id="subcategory" >
          </a>
        </div>
  </div>
</div>
      </div>
    </div>
  </div>

</div>
<script type="text/javascript">
  $('.categoryList').on('click', function(){
  var cat_id = $(this).attr('value');
  var url = "localhost:8000/api/getSubcategory/"+cat_id;
  $.ajax({
      type: "GET",
      url: url,
      dataType: "JSON",
      success: function(res)
      {
        // amusing res = {"3":"home","4":"home duplex"}; 
        var html = "";
        $.each(res, function (key, value) {
             html += "<option value="+key+">"+value+"</option>";
        });
        $("#subcategory").html(html);
      }
  });
});
</script>
@endsection

This is output but not save in database