Skip to main content
A cart holds the purchasable items a customer intends to buy, together with the addresses and shipping selection needed to calculate totals and, eventually, create an order.

Overview

A cart belongs to a channel and a currency, optionally to an authenticated user and a customer, and holds a collection of lines, each pointing at a purchasable item (typically a product variant).
Cart totals (subTotal, total, taxTotal, and so on) are calculated by the cart calculation and exposed as public properties on the Lunar\Core\Models\Cart instance, each a Lunar\Core\DataObjects\PriceValue. After every calculation the result is also written to the carts and cart_lines rows as a snapshot, which calculate() serves on later requests while it is fresh. See Calculating totals. Once a cart is converted to an order, the totals are copied onto the order.

Cart model

Fields

Relationships

Scopes

Lunar\Core\Models\Cart uses SoftDeletes. This is not a lifecycle state on the cart itself — it lets order-tied carts hang around for replay and audit rather than being permanently removed.

Cart line model

Fields

Relationships

purchasable_type / purchasable_id on a cart line are always set — every cart line points at a real purchasable. This is unlike an order line, where the same morph is nullable for self-describing lines such as shipping or ad-hoc charges. A cart never produces a purchasable-less line.
Don’t confuse the purchasable morph relation with Lunar\Core\Enums\SellingPolicy, the always / in_stock / in_stock_or_on_backorder mode stored on ProductVariant::$selling_policy (renamed from purchasable in v2). The two are unrelated: the morph is what is in the line, the selling policy is whether the underlying variant can currently be sold, and it’s what canBeFulfilledAtQuantity() checks when a line is added or updated (see Adding and updating lines).

Cart address model

Fields

Relationships

A cart holds at most one address per type — adding an address of a given type replaces any existing one of that type.

Retrieving and using carts

Lunar\Core\Facades\CartSession manages the cart for the current visitor, backed by Lunar\Core\Managers\CartSessionManager. It is bound scoped in the container, so under Octane or a queue worker each request or job gets its own instance — see Session-scoped, not a singleton below.
By default CartSession::current() does not create a cart. Set lunar.cart_session.auto_create to true to have it create one automatically, or call CartSession::manager(), which always returns a cart.
Configuration lives in packages/core/config/cart_session.php: When no cart ID is in the session, CartSession resolves the cart in this order:
  1. The remember cookie, for a guest cart.
  2. The authenticated user’s latest unmerged, active cart, so a returning logged-in user picks their existing cart back up.
If neither finds a cart, a new one is created (when auto_create is enabled or manager() is called).

Remembering guest carts

A guest cart normally lives only as long as the session. To let a store keep a short session lifetime without guests losing their carts, CartSession also points a long-lived cookie at the guest cart. When the session has expired, the cookie restores the cart into the new session. The cookie holds a random 40-character token. Only its SHA-256 hash is stored, in the cart’s remember_token column, so reading the database does not reveal a working cookie value. The cookie is managed whenever the session’s cart changes: A cart is only restored from the cookie when it has no user_id, has not been merged into another cart, and has no placed order. This means that after a user logs out on a shared device, the next visitor cannot pick up that user’s cart. Because the expiry is refreshed on each restore rather than on each request, a guest who returns at least once within remember.lifetime keeps their cart, and ordinary requests do not send an extra Set-Cookie header. The token is not rotated on restore: parallel requests at the start of a session all carry the same cookie, and rotating it would cause all but one of them to clear it. The cookie takes its path, domain, secure and same_site settings from config/session.php, and is always HttpOnly. It is excluded from Laravel’s EncryptCookies middleware, because the value is already a random secret and encrypting it would stop the cart being found on routes that do not run that middleware (for example API routes).
Keep remember.lifetime shorter than lunar.cart.prune_tables.prune_interval, and leave auto_create set to false. With auto_create off, crawlers that never add to cart are not given a cart or a cookie.
To turn the behavior off, set remember.enabled to false:

Creating a cart directly

Carts can also be created directly, bypassing the session, which is useful for APIs or background jobs:

Setting the channel and currency

Setting the currency on an existing cart updates currency_id on the cart and refreshes it from the database. The update also marks the persisted totals stale, so the next calculate() runs the calculation and prices in the new currency.

Associating a user

$policy is either merge (the default) or override. On merge, the user’s existing active cart is merged into the given cart via MergeCart; matching lines (same purchasable and meta) have their quantities combined, others are copied across. On override, the user’s existing cart is marked as merged into itself and abandoned in favor of the given cart. This mirrors lunar.cart.auth_policy, applied automatically by CartSessionAuthListener when a user logs in.

Forgetting the session cart

Removes the cart ID from the session and clears the cart’s remember cookie. Deletes the cart itself unless $delete is passed as false or lunar.cart_session.delete_on_forget is false.

Adding and updating lines

Cart lines are also managed through verb methods on the Cart model itself, which is what CartSession delegates to.
add() runs the Lunar\Core\Enums\StepList::AddToCartValidation validators (quantity, stock, and channel/customer-group availability by default) before adding or incrementing the line, then refreshes and recalculates the cart. If a line for the same purchasable and meta already exists, its quantity is incremented rather than a new line being created.
Stock validation calls $purchasable->canBeFulfilledAtQuantity($quantity), which for a Lunar\Core\Models\ProductVariant reads its Lunar\Core\Enums\SellingPolicy (Always, InStock, InStockOrOnBackorder) — a variant with policy Always is always fulfillable regardless of stock.

Addresses and tax zone

$address accepts either an array of address fields or a model implementing Lunar\Core\Contracts\Addressable. Setting an address replaces any existing address of the same type on the cart. Setting the shipping address clears any manually-set tax_zone_id by default (pass $clearTaxZone = false to keep it), so tax resolution falls back to the address-derived zone.

Shipping

Shipping options are resolved through Lunar\Core\Facades\ShippingManifest — see Extending Shipping for how carriers register options. CartSession::getShippingOptions() returns the options available for the session’s current cart.

Discounts

Coupon codes and cart-level discounts are applied during calculation, not through a dedicated verb method — set coupon_code on the cart and recalculate:
See Discounts for how discounts are matched and applied. After calculation, $cart->discounts, $cart->discountTotal, $cart->discountBreakdown, $cart->promotions, and $cart->freeItems describe what was applied.

Calculating totals

calculate() delegates to the Lunar\Core\Contracts\Actions\Carts\CalculatesCart action, which takes the cheapest route to a set of totals:
  1. If the cart and every line already carry a total in memory (isCalculated()), return the cart as is.
  2. If the persisted snapshot is fresh and covers every loaded line, hydrate the properties from the row without running the calculation. See Persisted totals.
  3. Otherwise run the calculation, then persist the result.
recalculate() skips the first two routes and always runs the calculation. Use it wherever a guaranteed-fresh total matters: checkout, payment amount checks, and any code that reads the cart straight after writing to it outside the verb methods. The calculation runs the Lunar\Core\Enums\StepList::CartCalculation step list, in order:
  1. Lunar\Core\Pipelines\Cart\CalculateLines — for each line, runs the line modifiers’ calculating() hook, prices the line through the StepList::CartLinePricing steps (GetUnitPrice by default), sets its subtotal, runs the line modifiers’ subtotalled() hook, then derives the line’s discounted subtotal and total from the subtotal
  2. Lunar\Core\Pipelines\Cart\ApplyShipping — resolves and applies the shipping option
  3. Lunar\Core\Pipelines\Cart\CalculateShippingSubTotal
  4. Lunar\Core\Pipelines\Cart\ApplyDiscounts — matches and applies eligible discounts
  5. Lunar\Core\Pipelines\Cart\CalculateTax
  6. Lunar\Core\Pipelines\Cart\Calculate — sums line totals, discounts, and shipping into the cart-level totals
Each stage populates public properties on the cart (and its lines) as Lunar\Core\DataObjects\PriceValue instances: A PriceValue exposes ->value (the integer minor-unit amount), ->decimal(), and ->format(), resolved against the cart’s currency. It also supports add(), subtract(), multiply(), and clampToZero() for combining amounts in custom pipeline stages.
Registered modifiers run around these steps. Lunar\Core\Modifiers\CartModifier::calculating() runs before the first step. After the last step, each line’s Lunar\Core\Modifiers\CartLineModifier::calculated() hook runs with final totals, followed by CartModifier::calculated(). Custom logic is added as a modifier at these fixed points, or as a step at a precise position in a step list. Modifiers and steps run only when the calculation runs, not when a fresh snapshot is served, so data they record beyond the standard totals belongs in meta. See Extending Carts.

Persisted totals

After each calculation, Lunar writes the resulting totals to the carts row and to each cart_lines row, together with the revision the cart was at and the time of the calculation. The next calculate() serves those columns instead of running the calculation while the snapshot is fresh, meaning both of the following hold:
  • calculated_revision equals the cart’s current revision, so nothing on the cart has changed since the snapshot was written.
  • calculated_at is within lunar.cart.totals.ttl seconds of now.
A calculation that uses an estimated shipping option, or a cart or line with unsaved changes, is never served from the snapshot or written to it.
The TTL bounds staleness from inputs the cart cannot observe: a price edit, a discount reaching its end date, a tax zone change, or a carrier repricing its rates all change the answer without touching the cart. Setting ttl to 0 means the snapshot is never served. It is still written, so the columns stay populated for reporting.
A hydrated cart is indistinguishable from a freshly calculated one for everything a storefront renders: every PriceValue property on the cart and its lines, the breakdowns, discounts, freeItems, and fingerprint() all match. The computed properties on Lunar\Core\Models\CartAddress (shippingOption, shippingSubTotal, shippingTaxTotal, shippingTotal, taxBreakdown) are populated only by a calculation. Order creation forces one before it reads them.
The total column shares its name with the total property on both Cart and CartLine. The property wins for $cart->total, $line['total'], and pluck('total'), so existing reads keep returning a PriceValue. Read the raw column through getAttribute('total') or getRawOriginal('total'), or query it directly for reporting, for example Cart::where('total', '>', 10000).

Invalidation

Every change to a cart increments its revision, which makes the snapshot stale until the next calculation writes a new one. The increment always happens in SQL (revision = revision + 1), so two requests changing the same cart at once cannot lose an update. Every verb method (add(), updateLine(), remove(), setShippingAddress(), setShippingOption(), setTaxZone(), associate(), and the rest) writes through one of these paths and then recalculates, so the snapshot is stale for only as long as the verb takes. Code that writes carts, cart_lines, or cart_addresses rows through the query builder bypasses the observers and must call $cart->invalidateTotals() itself. The write is guarded on the revision the cart was loaded at. If another request changed the cart while this one was calculating, the snapshot is skipped, the in-memory totals stay valid for the current request, and the next request recalculates. The snapshot columns are never cleared, so the last calculated figures remain queryable even while stale: a cart holding a stale snapshot is one where calculated_revision is null or differs from revision. None of these writes appear in the activity log; the snapshot columns, revision, calculated_revision, and calculated_at are excluded on both Cart and CartLine.

Converting a cart to an order

createOrder() recalculates the cart, runs the StepList::OrderCreateValidation validators (ValidateCartForOrderCreation by default — quantity, stock, and address/shipping completeness), then delegates to the CreatesOrder action contract to create or update the draft order tied to the cart, mark any used discounts as consumed, and return the resulting Lunar\Core\Models\Order.
CartSession::createOrder() is the session-aware equivalent — it creates the order from the session’s current cart and, by default, calls forget() afterwards. A cart’s fingerprint() produces a hash of its lines, user, currency, and coupon code, used to detect whether a cart has changed since a price or order was last calculated for it.

Pruning carts

Lunar\Core\Console\Commands\PruneCarts deletes carts (and their lines and addresses) matched by the StepList::CartPruning step list. By default this excludes carts with orders and carts merged into another cart, and only targets carts older than lunar.cart.prune_tables.prune_interval days (default 90). Pruning is disabled by default (lunar.cart.prune_tables.enabled); schedule the command once enabled. Restoring a cart from the remember cookie touches the cart’s updated_at, so a guest cart that is still being restored is not treated as abandoned.

Session-scoped, not a singleton

Lunar\Core\Contracts\CartSession is bound scoped in the container, not singleton — it memoizes the current cart for the life of one request or job. Under Octane or a queue worker, a singleton binding would persist across requests and leak one visitor’s cart into the next; scoped is discarded when the request or job ends.