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">×</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