Adding and removing products from a collection logic in Laravel
Hi guys, I am a bit confused about how I can implement some Logic here in Laravel.
I have three tables, products, collections, and collection_product. I want a user to be able to add products to collections and remove them. on the products table, I have collection_id and on the collection_products table, I have a collection_id and product_id. When a user adds products to a collection, create a new collection_product where I take the id of the product and the collection id and add them to the collection_product table. So I am stuck at the point where I am trying how can fetch all the products belonging to a collection, using the collection's id.
You do not need the collection_id column on the products table because you are describing a many-to-many relationship. Your Models each should have a belongsToMany relationship defined:
// Collection Model
public function products()
{
return $this->belongsToMany(Product::class);
}
// Product Model
public function collections()
{
return $this->belongsToMany(Collection::class);
}
Now, you can get the Products associated with a Collection using:
$collection = Collection::with('products')->findOrFail($collectionId); // single Collection
// or
$collections = Collection::with('products')->get(); // collection of Collections
You can iterate:
@foreach($collection->products as $product)
<p>{{ $product->name }}</p>
// ...
@endforeaach
@tykus Thank you for the insight but What I am concerned with most is the functionality where a product can be added and removed from a collection. How do I achieve that?