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('AppModelsCategory'); }
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?
Advertisement
Answer
You can get pivot table columns the following way:
Product model
public function category() { return $this->belongsToMany('AppModelsCategory')->withPivot('selected'); }
edit product page View:
<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.
<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>