As you've provided very little information to assist you with, some assumptions are going to be made such as naming conventions and relationship types.
Product.php
Add a carts relationship to your Product model. This assumes a Product can belong to many Carts.
public function carts()
{
return $this->belongsToMany(Cart::class);
}
Cart.php
Add a products relationship to your Cart model. This assumes a Cart can have many Products.
public function products()
{
return $this->belongsToMany(Product::class);
}
Create a pivot table which will maintain the relationships between Carts and Products:
php artisan make:migration create_cart_product_table
Then add your relationship foreign keys to the migration:
public function up()
{
Schema::create('cart_product', function (Blueprint $table) {
$table->id();
$table->foreignId('cart_id')->constrained();
$table->foreignId('product_id')->constrained();
$table->timestamps();
});
}
To add Products to a Cart, you can use the attach or sync methods, for example:
$products = Product::inRandomOrder()->take(5)->pluck('id');
Cart::create(['user_id' => 1])->products()->attach($products);
The above will get 5 Products (at random) from your products table, then create a new Cart with the given user id and attach those Products to the Cart.
To retrieve a Cart and it's associated Products, you would do the following:
$cart = Cart::where('id', $id)->with('products');
The $cart variable can be passed to a view or in a json response where after you can iterate over the Products in the Cart.
$cart = Cart::where('id', $id)->with('products');
return view('cart', compact('cart'));
blade view
<ul>
@foreach ($cart->products as $product)
<li>{{ $product->name }}</li>
@endforeach
</ul>
If you want to get all the Cart records for a given User, you would do the following:
$carts = Cart::where('user_id', $id)->with('products')->get();
return view('carts', compact('carts'));
blade view
@foreach ($carts as $cart)
{{ $cart->id }}
<ul>
@foreach ($cart->products as $product)
<li>{{ $product->name }}</li>
@endforeach
</ul>
<hr />
@endforeach
Or something to that effect.
$products = Product::whereHas('carts', function ($query) use ($userId) {return $query->where(['user_id' => $userId])})->get();.