Back

Laravel edit Product, set correct selected (with many-to-many)


I have a system where a User has Shops and Shops have Products.

Now a Shop can have many Products, and a Product can belong to many Shops. When a User adds a new Product he/she can choose for which Shop he/she wants to add it

Shops

+----+---------+----------------+
| id | user_id |      name      |
+----+---------+----------------+
|  1 |       1 | My First Shop  |
|  2 |       1 | My Second Shop |
+----+---------+----------------+

Shop_Products

+---------+------------+-----------+
| shop_id | product_id |   image   |
+---------+------------+-----------+
|       1 |          1 | beer.jpg  |
|       1 |          2 | wine.jpg  |
|       1 |          3 | vodka.jpg |
+---------+------------+-----------+

My issue is when a User edits a Product I want to pre-populate the Shop select dropdown with the current Shop this product is assigned to..

But offcourse the following query returns a Collection hence the many-to-many

$product = Product::findOrFail($id)->shops

in my view, to set the correct select option selected I'm trying the following

@foreach(\Auth::user()->shops as $shop)
    <option value="{{ $shop->id }}" @if($shop->id == $product->shop->id) selected @endif>{{ $shop->description }}</option>
@endforeach

$product->shop->id isn't working, because $product->shop is a collection

Looking forward to your ideas! Thank you


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us