Retrieving Selected & non-selected products with pivot table Laravel

  admin, laravel, php, product, voyager

I stored related items from Add product form. I want to retrieve those stored items in edit product form so user can remove stored items and display all other products from product table to select new items. My view is

<select class="form-control select2-taggable select2-hidden-accessible" name="related_id[]" multiple>
 <ul class="select2-selection__rendered">
  @foreach($relatedproducts as $related)
   <li class="select2-selection__choice" title="{{$related->name}}" data-select2-id="{{$related->id}}">{{$related->name}} </li>
  @endforeach
 </ul>
 @foreach($relatedproducts as $product)
  <option class="form-control" value="{{$product->id}}" > {{$product->name}} </option>
 @endforeach
</select>

Add Product is working well. But I want to edit the existing product.
The ProductController

public function edit(Request $request, $id)
{
 $product = RelatedProduct::where('product_id', '=', $id)->firstOrFail();
 $relatedproducts = $product->products()->get();

$products = Product::all();

return view(compact('products', 'relatedproducts');
}

ProductModel:

public function related() {
        return $this->belongsToMany('AppProduct', 'related_products', 'product_id', 'related_id');
    }

RelatedProduct Model:

protected $table = 'related_products';
    protected $fillable = ['product_id', 'related_id'];

    public function products() {
        return $this->belongsToMany('AppProduct', 'related_products', 'product_id', 'related_id');
    }

I’m trying to fetch the products but its not showing in the view.

Source: Laravel

Leave a Reply