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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Pushing behavior like add and subtotal onto the model keeps cart logic in one place instead of scattering it across controllers.
- 2firstOrNew lets you upsert a related row without a separate exists check, treating new and existing items uniformly.
- 3Casts and touch quietly manage timestamps so business methods stay focused on the domain.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/modeling-a-shopping-cart-in-laravel-explained-php-8e6d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.