I am using dynamic dependent dropdown list.Where subcategory is dependent on category.In my edit view I want to get my previous selected dropdown value in my form.But I only get the selected category..value. But not the subcategory value...I dont know how to fix it
<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>
here is my ajax code
<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>
controller
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'));
}
route
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'));
DB::table...
will return a object, but you need to have an array, so you can use or all()
or toArray()
after the pluck(...)
call like this:
$subcategories = DB::table("subcategories")->where("category_id",$id)->pluck("subcategory_name","id")->all();