I have three tables: products, categories and category_product.
In my edit form page I'm displaying the categories and subcategories values in a select box. The chosen category options are saved in the pivot table category_product. This table has product_id and category_id.
Here's my code.
Product model
public function category() {
return $this->belongsToMany('App\Models\Category');
}
Category model:
public function products()
{
return $this->belongsToMany(Product::class);
}
edit product page view:
<select name="category_id[]" class="form-control" multiple size = 10>
@foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}">{{ $parentCategory->name }}</option>
@if(count($parentCategory->subcategory))
@include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
@endif
@endforeach
</select>
subcats-select view
@foreach($subcategories as $subcategory)
<option value="{{ $subcategory->id }}">---{{ $subcategory->name }}</option>
@if(count($subcategory->subcategory))
@include('includes.subcats-select',['subcategories' => $subcategory->subcategory])
@endif
</div>
@endforeach
How can I put "selected" attribute to the chosen category options, so when I edit the page to apply the changes properly?