I'm working on a project with Laravel 8, where I need to make a dynamic dropdown in a form to create categories. The first dropdown must show stores and the second one should show the categories of that store. I don't know if I should do this with javascript or some other way.
<label for="store_id">Store</label>
<select id="store_id" name="store_id" class="custom-select">
@foreach($stores as $store)
<option value="{{ $store->id}}">{{ $store->name}}</option>
@endforeach
</select>
<label for="parent_category">Parent Category</label>
<select id="parent_category" name="parent_category" class="custom-select">
</select>
| id | store_id | parent_category_id | name |
|---|
| id | name |
|---|
public function create()
{
$stores = Store::all();
$categories = Category::all();
$data= [
'stores ' => $stores ,
'categories ' => $categories
];
return view('category.create')->with($data);
}
You can achieve this approach with jQuery:
get store categories through relationship, depending on your relation type One to Many, Many to Many, etc:
public function Storecategories()
{
return $this->hasMany('App/Models/Categories','store_id');
}
In your controller function and get store categories:
//return store categories with ajax response using relationship
$store_categories = StoreModel::find($store_id)->Storecategories()
//if any where clause you want to add
->where('Your conditions')
->get();
return response()->json(['store_categories'=>$store_categories->toArray() ]);
Send ajax request on selecting store, get categories array and create categories html dynamically:
//Perform action on selection of store
$(document).on('change','#store_id',function(){
$.ajax({
type: "POST",
url: Your ajax url,
data[store_id:stroe_id , _token:token],
success: function (data) {
let categories = data.store_categories;
let html = '';
$.each(categories ,function(i,v){
html += '<option value="'+v.id+'">'+v.name+'</option>';
});
$("#parent_category").html(html);
}
});
});