Using Laravel 5.3, I have a database consisting of users, products and wishlists joined bya a pivot table product_wishlist. The schema is below:
USERS WISHLISTS PRODUCTS PRODUCT_WISHLIST
------------- ------------- -------------- ---------------
id id id product_id
name name name wishlist_id
user_id
In App/Wishlist.php
public function products()
{
return $this->belongsToMany(Product::class, 'product_wishlist');
}
public function owner()
{
return $this->belongsTo(User::class);
}
In App/product.php
public function wishlists()
{
return $this->belongsToMany(Whishlist::class, 'product_wishlist');
}
A user can create wishlists and add products to wishlists.
In a product page, I'm trying show all wishlists of logged user.
$wishlists = Auth::user()->wishlists;
But i also want retrive if each wishlist contains the product (i will add a "add to wishlist" button near of each wishlist only if this not contains the product yet).
I edit after the Kabelo answer:
What i want is show a single product page, and in the sidebar shows all wishlists of the logged user (each user has your own wishlists): wishlist1 (add to list), wishlist2 (add to list),... but if for example the product of this page is already in the wishlist2 then no show "(add to list)". In these cases I could show "(remove from list)"
$user->wishlist->products...and of course you can count them and make checks - Mruf