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
JavaScript
x
public function category() {
return $this->belongsToMany('AppModelsCategory');
}
Category model:
JavaScript
public function products()
{
return $this->belongsToMany(Product::class);
}
edit product page view:
JavaScript
<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
JavaScript
@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?
Advertisement
Answer
You can get pivot table columns the following way:
Product model
JavaScript
public function category() {
return $this->belongsToMany('AppModelsCategory')->withPivot('selected');
}
edit product page View:
JavaScript
<select name="category_id[]" class="form-control" multiple size = 10>
@foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}" selected="{{ $parentCategory->pivot->selected }}">
{{ $parentCategory->name }}
</option>
@if(count($parentCategory->subcategory))
@include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
@endif
@endforeach
</select>
EDIT: While the above answer might be helpful for others, it doesn’t answer the question. So here’s my second try after some clarification in the chat.
JavaScript
<select name="category_id[]" class="form-control" multiple size = 10>
@foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}"{{ $product->category->contains($parentCategory->id) ? 'selected' : '' }}>
{{ $parentCategory->name }}
</option>
@if(count($parentCategory->subcategory))
@include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
@endif
@endforeach
</select>