1

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?

shaedrich
  • 5,457
  • 3
  • 26
  • 42
user2519032
  • 819
  • 1
  • 18
  • 34

1 Answers1

2

You can get pivot table columns the following way:

Product model

public function category() {
  return $this->belongsToMany('App\Models\Category')->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>
shaedrich
  • 5,457
  • 3
  • 26
  • 42