我使用的是动态相关的下拉列表。子类别取决于类别。在我的编辑视图中,我想在表单中获取以前选择的下拉值。但是我只获取所选的类别。值。但是不是子类别值...我不知道如何解决它
<div class="form-row col-md-12">
<div class="form-group col-md-6" style="margin-left: 5px">
<label for="inputError" class="control-label">Category</label>
<select class="chosen-select form-control" name="category">
<option value="">Select category</option>
@foreach ($categories as $category)
<option value="{{ $category->id }}" {{$product->category_id==$category->id?'selected':''}}>{{$category->category_name}}</option>
@endforeach
</select>
{{$errors->first('category')}}
</div>
<div class="form-group col-md-6" style="margin-left: 5px" >
<label for="inputError" class="control-label">Sub Category</label>
<select class=" chosen form-control" id="subcategory" name="subcategory"></select>
{{$errors->first('subcategory')}}
</div>
</div>
这是我的ajax代码
<script type="text/javascript">
$(document).ready(function() {
$('select[name="category"]').on('change', function() {
var stateID = $(this).val();
console.log(stateID)
if(stateID) {
$.ajax({
url: '/myform/ajax/'+stateID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="subcategory"]').empty();
$.each(data, function(key, value) {
$('select[name="subcategory"]').append('<option value="' + key + '">'+ value +'</option>');
});
}
});
}else{
$('select[name="subcategory"]').empty();
}
});
});
</script>
控制器
public function myformAjax($id)
{
$subcategories = DB::table("subcategories")
->where("category_id",$id)
->pluck("subcategory_name","id");
return json_encode($subcategories);
}
public function edit($id)
{
$categories = Category::latest()->get();
$product = Product::findOrFail($id);
return view('product.edit',compact('categories','product'));
}
路线
Auth::routes();
Route::group(['middleware' => 'auth'], function (){
Route::get('/home', 'HomeController@index')->name('home');
Route::resource('group', 'GroupController');
Route::resource('company', 'CompanyController');
Route::resource('slider', 'SliderController');
Route::resource('category', 'CategoryController');
Route::resource('subcategory', 'SubcategoryController');
Route::resource('product', 'ProductController');
});
Route::get('myform/ajax/{id}',array('as'=>'myform.ajax','uses'=>'HomeController@myformAjax'));
答案 0 :(得分:0)
DB::table...
将返回一个对象,但是您需要一个数组,因此您可以在all()
调用之后使用或toArray()
或pluck(...)
,如下所示:>
$subcategories = DB::table("subcategories")->where("category_id",$id)->pluck("subcategory_name","id")->all();