php 45 lines · 7 steps

Modeling a shopping cart in Laravel

An Eloquent model ties a cart to its owner and items, then layers cart operations like adding products and computing a subtotal.

Explained by highlit
1class Cart extends Model
2{
3 protected $fillable = ['user_id'];
4 
5 protected $casts = [
6 'abandoned_at' => 'datetime',
7 ];
8 
9 public function user(): BelongsTo
10 {
11 return $this->belongsTo(User::class);
12 }
13 
14 public function items(): HasMany
15 {
16 return $this->hasMany(CartItem::class);
17 }
18 
19 public function add(Product $product, int $quantity = 1): CartItem
20 {
21 $item = $this->items()->firstOrNew(['product_id' => $product->id]);
22 
23 $item->quantity += $quantity;
24 $item->unit_price = $product->price;
25 $item->save();
26 
27 $this->touch();
28 
29 return $item;
30 }
31 
32 public function subtotal(): int
33 {
34 return $this->items->sum(fn (CartItem $item) => $item->quantity * $item->unit_price);
35 }
36 
37 public function mergeGuestCart(array $guestItems): void
38 {
39 foreach ($guestItems as $productId => $quantity) {
40 if ($product = Product::find($productId)) {
41 $this->add($product, $quantity);
42 }
43 }
44 }
45}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Pushing behavior like add and subtotal onto the model keeps cart logic in one place instead of scattering it across controllers.
  2. 2firstOrNew lets you upsert a related row without a separate exists check, treating new and existing items uniformly.
  3. 3Casts and touch quietly manage timestamps so business methods stay focused on the domain.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Modeling a shopping cart in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code