首页 > 解决方案 > Laravel 8 中的动态相关下拉菜单

问题描述

我想根据父类别过滤子类别数据。我在所有类别中都获得了我的所有子类别。我尝试了许多来自 stackoverflow 和 youtube 的旧答案,但没有奏效。

我想在我的文章发布表单中使用这个过滤器。

create.article.blade.php

<form action="{{ URL::to('post-article-form') }}" method="post" enctype="multipart/form-data">
        @csrf
        <div class="form-group">
            <label for="exampleInputEmail1">Article Name <b style="color: red">*</b></label>
            <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter article title" name="articleTitle" required>
        </div>
        <div class="form-group">
            <label for="exampleInputEmail1"> Select Article category </label>
            <select class="form-control" name="category" id="category" required>
                <option value=""> Select </option>
                @foreach($categories as $category)
                    <option value="{{ $category->id }}"> {{ $category->name }}</option>
                @endforeach
            </select>
        </div>
        <div class="form-group">
            <label for="exampleInputEmail1"> Select Sub category </label>
            <select class="form-control" name="subCategory" id="subCategory" required>
                <option value=""> Select </option>
                @foreach($subCategories as $subCategory)
                    <option value="{{ $subCategory->id }}"> {{ $subCategory->name }}</option>
                @endforeach
            </select>
        </div>

我想根据父类别过滤子类别数据。我在所有类别中都获得了我的所有子类别。我尝试了许多来自 stackoverflow 和 youtube 的旧答案,但没有奏效。

我想在我的文章发布表单中使用这个过滤器。

create.article.blade.php

<form action="{{ URL::to('post-article-form') }}" method="post" enctype="multipart/form-data">
        @csrf
        <div class="form-group">
            <label for="exampleInputEmail1">Article Name <b style="color: red">*</b></label>
            <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter article title" name="articleTitle" required>
        </div>
        <div class="form-group">
            <label for="exampleInputEmail1"> Select Article category </label>
            <select class="form-control" name="category" id="category" required>
                <option value=""> Select </option>
                @foreach($categories as $category)
                    <option value="{{ $category->id }}"> {{ $category->name }}</option>
                @endforeach
            </select>
        </div>
        <div class="form-group">
            <label for="exampleInputEmail1"> Select Sub category </label>
            <select class="form-control" name="subCategory" id="subCategory" required>
                <option value=""> Select </option>
                @foreach($subCategories as $subCategory)
                    <option value="{{ $subCategory->id }}"> {{ $subCategory->name }}</option>
                @endforeach
            </select>
        </div>

我在下面的脚本中使用了这个过滤器,但没有用。我得到相同的结果意味着。选择任何类别后的所有子类别。

<script>
     $('#category').on('change',function(e){
      console.log(e);
      var cat_id = e.target.value;
       //ajax

      $.get('/ajax-subcat?cat_id='+cat_id, function(data){
         //subcategory
        $('#subCategory').empty();
        $('#subCategory').append($("<option></option>").val("").html("--Select Sub Category--"));
        $.each(data,function(index, subcatObj){
       $('#subCategory').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
        })
    })
});
</script>

我的 web.php 路线

//sub category
Route::get('add-sub-category', [SubCategoryController::class, 'create']);
Route::post('post-sub-category-form', [SubCategoryController::class, 'store']);
Route::get('subcategories', [SubCategoryController::class, 'index']);

Route::get("/ajax-subcat", function (Request $request){
    $cat_id = $request-> Input::get('cat_id');
    $subCategories = SubCategory::where('category_id',$cat_id)->get();

    return response()->json($subCategories);

    });

在此处输入图像描述

标签: ajaxlaraveleloquent

解决方案


我只是为下拉选择添加路线

route::get('dropdownlist/getsubcategories/{id}', [ArticleController::class , 'getSubCategories']);

创建控制器并调用查询方法根据类别id获取子类别。

public function getCategories()
    {
        $categories = DB::table('categories')->pluck("name","id");
        return view('article.create',compact('categories'));
    }

    public function getSubCategories($id)
{
        $subcategories = DB::table("sub_categories")->where("category_id",$id)->pluck("name","id");
        return json_encode($subcategories);
}

并在资源文件中使用了 Ajax。

创建.blade.php

<script type="text/javascript">
            jQuery(document).ready(function ()
            {
                    jQuery('select[name="category"]').on('change',function(){
                       var categoryID = jQuery(this).val();
                       if(categoryID)
                       {
                          jQuery.ajax({
                             url : 'dropdownlist/getsubcategories/' +categoryID,
                             type : "GET",
                             dataType : "json",
                             success:function(data)
                             {
                                console.log(data);
                                jQuery('select[name="subCategory"]').empty();
                                jQuery.each(data, function(key,value){
                                   $('select[name="subCategory"]').append('<option value="'+ key +'">'+ value +'</option>');
                                });
                             }
                          });
                       }
                       else
                       {
                          $('select[name="subCategory"]').empty();
                       }
                    });
            });
            </script>

推荐阅读