Skip to content

Cart

Manage shopping carts with pipeline-based calculation, discount validation, tax integration, and order conversion.

The shopper/cart package handles everything between "Add to cart" and "Place order". It manages cart lines, validates stock, applies discounts, calculates taxes, and converts completed carts into orders. All through a clean, testable API.

Every monetary value is stored in cents as an unsigned integer. A product priced at $25.00 is stored as 2500.

How It Works

The cart system has five main pieces:

  1. CartManager handles cart operations: add, update, remove, apply coupons, calculate totals
  2. CartSessionManager persists the current cart in the session for storefront use
  3. Pipeline system calculates totals through a configurable chain of pipes (subtotals, then discounts, then taxes, then the total)
  4. DiscountValidator enforces coupon rules: eligibility, usage limits, zones, minimum amounts
  5. CreateOrderFromCartAction converts a cart into an order within a database transaction

Cart Manager

The CartManager is the primary API for all cart operations. It is registered as a singleton and injected with the CartPipelineRunner.

use Shopper\Cart\CartManager;

$manager = resolve(CartManager::class);

Adding Items

Pass any model that implements Priceable, typically a Product or ProductVariant. The manager looks up the unit price from the purchasable's price list using the cart's currency. If the purchasable has no price in that currency, the line is created with a unit_price_amount of 0. A quantity below 1 throws an InvalidArgumentException.

$line = $manager->add($cart, $product);

$line = $manager->add($cart, $product, quantity: 3);

$line = $manager->add($cart, $variant, metadata: [
    'gift_wrap' => true,
    'message' => 'Happy birthday!',
]);

Adding the same purchasable twice increments the existing line's quantity instead of creating a duplicate. The line keeps the unit price and metadata it was created with.

$manager->add($cart, $product, quantity: 2); // quantity: 2
$manager->add($cart, $product, quantity: 3); // quantity: 5

Stock Validation

Every add() call, and every update() call that sets a quantity, checks available stock. If the purchasable implements Stockable, returns true from tracksInventory() and has allow_backorder set to false, an InsufficientStockException is thrown when the requested quantity exceeds available inventory. On add(), the requested quantity is the line's new total: the quantity already in the cart plus the quantity you add. Virtual and external products do not track inventory, so they are never checked.

use Shopper\Cart\Exceptions\InsufficientStockException;

try {
    $manager->add($cart, $product, quantity: 100);
} catch (InsufficientStockException $e) {
    $e->purchasable; // The product or variant
    $e->available;   // Current stock level
    $e->requested;   // Quantity that was requested
}

Products with allow_backorder set to true bypass stock checks entirely.

Updating a Line

$updated = $manager->update($cart, $lineId, [
    'quantity' => 5,
]);

$updated = $manager->update($cart, $lineId, [
    'metadata' => ['gift_wrap' => false],
]);

Only the quantity and metadata keys are written, any other key is ignored. The new quantity replaces the current one and goes through the same minimum and stock checks as add(). A $lineId that does not belong to the cart throws a ModelNotFoundException, in update() and in remove().

Removing Lines

$manager->remove($cart, $lineId);

$manager->clear($cart);

Applying Coupons

The applyCoupon() method validates that the discount code exists in the database before setting it on the cart. It does not check whether the discount is active or the cart is eligible: those rules run during the pipeline, along with the discount calculation (see Discount Validation).

use Shopper\Cart\Exceptions\InvalidDiscountException;

try {
    $manager->applyCoupon($cart, 'SUMMER20');
} catch (InvalidDiscountException $e) {
    // Discount code not found
}

$manager->removeCoupon($cart);

Removing a coupon also deletes all line adjustments that were created by the discount pipeline.

Adding Addresses

use Shopper\Core\Enum\AddressType;

$manager->addAddress($cart, AddressType::Shipping, [
    'first_name' => 'John',
    'last_name' => 'Doe',
    'address_1' => '123 Main St',
    'city' => 'New York',
    'postal_code' => '10001',
    'country_id' => $countryId,
]);

$manager->addAddress($cart, AddressType::Billing, $billingData);

If an address of the same type already exists, it is updated instead of duplicated.

Calculating Totals

use Shopper\Cart\Pipelines\CartPipelineContext;

$context = $manager->calculate($cart);

$context->subtotal;      // Sum of line subtotals (before discounts/tax)
$context->discountTotal; // Total discount amount
$context->taxTotal;      // Total tax amount
$context->total;         // Final total
$context->taxInclusive;  // Whether tax is included in prices
$context->lineSubtotals; // Subtotal of each line, keyed by line ID
$context->cart;          // The cart that was calculated

calculate() writes to the database: the discount and tax pipes delete and recreate the cart's CartLineAdjustment and CartLineTaxLine rows.

Completed Cart Guard

The line and coupon operations (add, update, remove, clear, applyCoupon, removeCoupon) throw CartCompletedException if the cart has already been completed. This prevents modifications after an order has been placed. addAddress() does not run this check.

use Shopper\Cart\Exceptions\CartCompletedException;

$cart->update(['completed_at' => now()]);

$manager->add($cart, $product); // throws CartCompletedException

Session Management

The CartSessionManager handles cart persistence in the HTTP session. Use it in your storefront to retrieve or create the current customer's cart.

Using the Facade

use Shopper\Cart\Facades\Cart;

$cart = Cart::current();

$cart = Cart::create();

$cart = Cart::create(['channel_id' => $channelId, 'zone_id' => $zoneId]);

Cart::use($existingCart);

Cart::associate($user);

Cart::forget();

Behavior

  • current() never returns a completed cart or a cart that was deleted. In those cases, and when the session holds no cart, it returns null, or a new cart when shopper.cart.session.auto_create is true
  • create() stores the new cart's ID in the session and sets the currency_code from shopper_currency() unless you pass one
  • use() stores an existing cart's ID in the session
  • associate() sets the customer_id on the current cart and does nothing when there is no current cart. Call this after login
  • forget() removes the cart ID from the session without deleting the cart itself

Models

Cart

Shopper\Cart\Models\Cart

The cart tables are sh_carts, sh_cart_lines, sh_cart_addresses, sh_cart_line_adjustments and sh_cart_line_tax_lines (sh_ is the default table prefix).

ColumnTypeNullableDescription
idbigintPrimary key
customer_idbigintYesFK to users
channel_idbigintYesFK to sh_channels
zone_idbigintYesFK to sh_zones
currency_codestringISO currency code (e.g. USD)
coupon_codestringYesApplied discount code
completed_attimestampYesSet when cart is converted to order
metadatajsonbYesCustom data
created_attimestamp
updated_attimestamp

Relationships

$cart->lines;            // HasMany<CartLine>
$cart->addresses;        // HasMany<CartAddress>
$cart->customer;         // BelongsTo, the model in config('auth.providers.users.model')
$cart->channel;          // BelongsTo<Channel>
$cart->zone;             // BelongsTo<Zone>

Methods

$cart->isCompleted();       // bool, checks if completed_at is set
$cart->shippingAddress();   // ?CartAddress, address with type Shipping
$cart->billingAddress();    // ?CartAddress, address with type Billing

CartLine

Shopper\Cart\Models\CartLine
ColumnTypeNullableDescription
idbigintPrimary key
cart_idbigintFK to cart
purchasable_typestringMorph type (Product, ProductVariant, etc.)
purchasable_idbigintMorph ID
quantityunsigned intItem quantity
unit_price_amountunsigned intPrice per unit in cents
metadatajsonbYesCustom data

Relationships

$line->cart;           // BelongsTo<Cart>
$line->purchasable;    // MorphTo, Product, ProductVariant, etc.
$line->adjustments;    // HasMany<CartLineAdjustment>
$line->taxLines;       // HasMany<CartLineTaxLine>

CartAddress

Shopper\Cart\Models\CartAddress
ColumnTypeNullableDescription
idbigintPrimary key
cart_idbigintFK to cart
typestringshipping or billing (AddressType enum)
country_idbigintYesFK to sh_countries
first_namestringYes
last_namestring
companystringYes
address_1stringStreet address
address_2stringYesApartment, suite, etc.
citystring
statestringYes
postal_codestring
phonestringYes

The full_name accessor combines first_name and last_name. The cart and country relations are BelongsTo.

CartLineAdjustment

Shopper\Cart\Models\CartLineAdjustment
ColumnTypeNullableDescription
idbigintPrimary key
cart_line_idbigintFK to cart line
discount_idbigintYesFK to discount
amountunsigned intDiscount amount in cents
codestringYesCoupon code

The cartLine and discount relations are BelongsTo.

CartLineTaxLine

Shopper\Cart\Models\CartLineTaxLine
ColumnTypeNullableDescription
idbigintPrimary key
cart_line_idbigintFK to cart line
tax_rate_idbigintYesFK to tax rate
codestringTax code
namestringTax name (e.g. "VAT")
ratedecimal(8,4)Tax rate (e.g. 20.0000 for 20%)
amountunsigned intTax amount in cents

The cartLine and taxRate relations are BelongsTo.

Calculation Pipeline

Cart totals are calculated through a pipeline of configurable steps. Each pipe receives a CartPipelineContext, performs its calculation, and passes it to the next pipe.

Default Pipeline

use Shopper\Cart\Pipelines\CalculateLines;
use Shopper\Cart\Pipelines\ApplyDiscounts;
use Shopper\Cart\Pipelines\CalculateTax;
use Shopper\Cart\Pipelines\Calculate;

// config/shopper/cart.php
'pipelines' => [
    'cart' => [
        CalculateLines::class,
        ApplyDiscounts::class,
        CalculateTax::class,
        Calculate::class,
    ],
],

Pipeline Steps

1. CalculateLines. Computes the subtotal for each line (unit_price_amount * quantity), stores it in $context->lineSubtotals and sums them into $context->subtotal.

2. ApplyDiscounts. If the cart has a coupon_code, loads the active discount with that code, validates it through DiscountValidator and calculates the discount amount. For percentage discounts, each applicable line gets round(lineSubtotal * value / 100). For fixed amount discounts, the amount is capped at the subtotal of the applicable lines and distributed proportionally across them, the last line taking the rounding remainder. Replaces the cart's CartLineAdjustment records.

3. CalculateTax. Resolves the shipping address country (and its state as the province code) and calculates tax for each line using the core TaxCalculator. The taxable amount per line is (lineSubtotal - discountAmount), and a line with nothing left to tax is skipped. Replaces the CartLineTaxLine records of each taxed line and sets $context->taxInclusive from the tax zone's is_tax_inclusive. Without a shipping address country, this step does nothing and taxTotal stays 0.

4. Calculate. Computes the final total. If tax is inclusive: total = subtotal - discountTotal. If tax is exclusive: total = subtotal - discountTotal + taxTotal. The minimum total is always 0.

Custom Pipeline

You can replace or extend the pipeline in config/shopper/cart.php. Add a custom pipe to handle shipping costs, loyalty points, or any other calculation:

'pipelines' => [
    'cart' => [
        CalculateLines::class,
        ApplyDiscounts::class,
        CalculateTax::class,
        Calculate::class,
        App\Cart\Pipes\ApplyShippingCost::class,
    ],
],

Calculate overwrites $context->total, so a pipe that changes the total goes after it. Each pipe is resolved from the container, so its constructor can receive dependencies. Like Shopper's own pipes, it implements handle(CartPipelineContext $context, Closure $next) (an __invoke() method with the same signature also works):

namespace App\Cart\Pipes;

use Closure;
use Shopper\Cart\Pipelines\CartPipelineContext;

final class ApplyShippingCost
{
    public function handle(CartPipelineContext $context, Closure $next): mixed
    {
        if ($context->subtotal < 5000) {
            $context->total += 990;
        }

        return $next($context);
    }
}

This pipe adds a $9.90 shipping fee to orders under $50.00. The total it returns is what CreateOrderFromCartAction stores as the order's price_amount.

Discount Validation

When a coupon is applied during the pipeline, the DiscountValidator runs a series of checks before the discount is calculated. A failed check does not throw: the pipeline skips the discount, discountTotal stays 0 and the code stays on the cart. Each check returns a translatable message from the shopper-cart::messages file. To tell the customer why a code does not apply, run the validator yourself:

use Shopper\Cart\CartManager;
use Shopper\Cart\Discounts\DiscountValidator;
use Shopper\Core\Models\Discount;

$context = resolve(CartManager::class)->calculate($cart);
$discount = Discount::query()->where('code', $cart->coupon_code)->firstOrFail();

$result = resolve(DiscountValidator::class)->validate($discount, $context);

if (! $result->valid) {
    return back()->with('error', $result->failureReason);
}

Validation Rules

RuleConditionError Key
Activediscount->is_active must be truediscount.not_active
Valuediscount->value must be greater than 0discount.invalid_value
PercentageA percentage discount's value must not exceed 100discount.invalid_percentage
Starteddiscount->start_at must not be in the futurediscount.not_started
Not expireddiscount->end_at must be null or in the futurediscount.expired
Usage limitTotal uses must be under the global limitdiscount.usage_limit_reached
Per-user limitIf usage_limit_per_user is true, the customer must have no earlier order with this discountdiscount.already_used
EligibilityIf eligibility is customers, the cart customer must be one of the selected customersdiscount.customer_not_eligible
Requires loginIf eligibility is customers or usage_limit_per_user is true, the cart must have a customer_iddiscount.requires_login
ZoneIf the discount has a zone_id, it must match cart->zone_iddiscount.not_available_in_zone
Minimum amountIf min_required is price, the cart subtotal before discount must reach min_required_value (in cents)discount.min_amount_not_reached
Minimum quantityIf min_required is quantity, the total quantity of all lines must reach min_required_valuediscount.min_quantity_not_reached

Discount Application Modes

Discounts support two application scopes via discount->apply_to:

  • Order (DiscountApplyTo::Order). Applies to all cart lines
  • Specific products (DiscountApplyTo::Products). Applies only to lines whose product is selected on the discount. A variant line matches when its parent product is selected

And two discount types:

  • Percentage. Each applicable line gets round(lineSubtotal * value / 100)
  • Fixed amount. The fixed amount (in cents, capped at the subtotal of the applicable lines) is distributed proportionally across applicable lines based on their share of that subtotal

Order Conversion

The CreateOrderFromCartAction converts a cart into an order and marks the cart as completed. This is the bridge between the storefront cart and the order management system.

use Shopper\Cart\Actions\CreateOrderFromCartAction;

$action = resolve(CreateOrderFromCartAction::class);
$order = $action->execute($cart);

What Happens

The entire operation runs inside a database transaction with a FOR UPDATE lock on the cart:

  1. Reserves the discount. If a coupon is applied, locks the discount row with lockForUpdate, validates the per-user limit against orders.discount_id, and increments total_use atomically only if the global usage_limit has not been reached
  2. Calculates totals. Runs the full pipeline to get final amounts
  3. Creates order addresses. Copies cart shipping/billing addresses to OrderAddress records
  4. Creates the order. With price_amount, tax_amount, currency_code, all foreign keys, and the discount snapshot (discount_id, discount_code, discount_type, discount_value_at_apply, discount_currency_code)
  5. Creates order items and reserves stock. One order item per cart line, including the discount amount from adjustments. For every line whose purchasable tracks inventory, stock is reserved through the StockReserver contract under a lockForUpdate row lock on the stockable. If the reservable quantity is less than the line quantity, InsufficientStockException is thrown and the whole transaction rolls back
  6. Creates order tax lines. Via CreateOrderTaxLinesAction, which calculates the tax of each order item again from the shipping address country, stores it as OrderTaxLine records and updates the tax_amount of the items and the order
  7. Marks cart as completed. Sets completed_at to prevent further modifications
  8. Dispatches CartCompleted event. With the cart and the created order, inside the transaction

If the cart has already been completed, CartCompletedException is thrown before any work begins. The FOR UPDATE lock prevents race conditions from concurrent checkout attempts.

Discount Limit Exceptions

Two failure paths around discount limits can short-circuit the transaction. DiscountLimitReachedException::global($code) is thrown when the global usage_limit was exhausted between cart validation and order commit. DiscountLimitReachedException::perUser($code) is thrown when the customer has already redeemed a discount with usage_limit_per_user set, or when a guest cart (no customer_id) uses such a discount. In both cases the transaction rolls back and no order is created.

use Shopper\Cart\Actions\CreateOrderFromCartAction;
use Shopper\Cart\Exceptions\DiscountLimitReachedException;

try {
    $order = resolve(CreateOrderFromCartAction::class)->execute($cart);
} catch (DiscountLimitReachedException $e) {
    return back()->with('error', 'This discount can no longer be used.');
}

For the full enforcement model, see Usage Limit Enforcement on the Discounts page.

Stock Reservation

Stock is reserved during checkout, inside the same transaction that creates the order, rather than asynchronously after the order commits. This closes the oversell window where two concurrent checkouts could each read the same last unit and both succeed. Reservation is delegated to the Shopper\Core\Contracts\StockReserver contract:

namespace Shopper\Core\Contracts;

use Illuminate\Database\Eloquent\Model;
use Shopper\Core\Models\Contracts\Stockable;

interface StockReserver
{
    public function reserve(Stockable $product, int $quantity, ?Model $reference = null, ?int $userId = null): int;
}

The default implementation, Shopper\Core\Stock\LockingStockReserver, takes a lockForUpdate row lock on the stockable, decreases the stock of the locations chosen by the StockAllocator contract (one decreaseStock() movement per location, with the order as reference), and returns the reserved quantity. When the locations together hold less than the requested quantity, it decreases nothing and returns what they hold. A product with allow_backorder enabled takes the whole quantity from its first location. See How Locations Connect to Stock for how the locations are chosen. The action throws InsufficientStockException when that amount is short of the requested quantity. Only purchasables that return true from tracksInventory() are reserved, so virtual and external products are skipped.

To plug in a custom strategy, such as reserving against an external warehouse system, bind your own implementation in a service provider:

use Shopper\Core\Contracts\StockReserver;

$this->app->bind(StockReserver::class, WarehouseStockReserver::class);

Events

EventDispatched WhenProperties
CartCompletedCart is converted to an orderCart $cart, Order $order (contracts from Shopper\Core\Models\Contracts)
CouponAppliedCoupon code is set on a cartCart $cart, string $code
CouponRemovedCoupon code is cleared from a cartCart $cart
use Shopper\Cart\Events\CartCompleted;
use Shopper\Cart\Events\CouponApplied;
use Shopper\Cart\Events\CouponRemoved;

Configuration

php artisan shopper:install publishes config/shopper/cart.php with the other Shopper configuration files. To publish the files that are missing, run:

php artisan vendor:publish --tag=shopper-config
// config/shopper/cart.php

return [
    'pipelines' => [
        'cart' => [
            CalculateLines::class,
            ApplyDiscounts::class,
            CalculateTax::class,
            Calculate::class,
        ],
    ],

    'session' => [
        'key' => 'shopper_cart',     // Session key for storing cart ID
        'auto_create' => false,      // Auto-create cart when current() is called
    ],

    'abandoned_after_minutes' => 60, // Minutes of inactivity before a cart counts as abandoned

    'prune_after_days' => 30,        // Days before abandoned carts are pruned

    'models' => [
        'cart' => Cart::class,       // Swappable via model contracts
        'cart_line' => CartLine::class,
    ],
];

Model Swapping

The Cart and CartLine models implement core contracts (Shopper\Core\Models\Contracts\Cart, Shopper\Core\Models\Contracts\CartLine) and use the HasModelContract trait. You can replace them with your own models:

// config/shopper/cart.php
'models' => [
    'cart' => App\Models\Cart::class,
    'cart_line' => App\Models\CartLine::class,
],

Your custom models must extend Shopper\Cart\Models\Cart and Shopper\Cart\Models\CartLine, otherwise Shopper throws an InvalidModelConfigurationException:

namespace App\Models;

use Shopper\Cart\Models\Cart as ShopperCart;

class Cart extends ShopperCart
{
}

Abandoned Carts

A cart is considered "abandoned" when it is not completed, has items, and has not been updated for a configurable period. Shopper provides both an admin interface and programmatic tools to manage abandoned carts.

Admin Panel

The admin panel includes an Abandoned Carts page under the Orders section, open to users with the browse_orders permission. It lists all carts that are not completed, have at least one line item, and have not been updated for at least abandoned_after_minutes. Administrators can view cart contents, the customer (if authenticated), the addresses, and the associated channel.

Configuration

Two config keys in config/shopper/cart.php control abandoned cart behavior:

'abandoned_after_minutes' => 60,  // Cart is "abandoned" after 60 minutes of inactivity
'prune_after_days' => 30,         // Carts not completed are deleted after 30 days without update

Querying Abandoned Carts

To find abandoned carts programmatically, for example to send recovery emails:

use Shopper\Cart\Models\Cart;

$abandonedCarts = Cart::query()
    ->whereNull('completed_at')
    ->whereHas('lines')
    ->whereNotNull('customer_id')
    ->where('updated_at', '<', now()->subMinutes(
        config('shopper.cart.abandoned_after_minutes', 60)
    ))
    ->with(['customer', 'lines.purchasable'])
    ->get();

Pruning

Old carts are deleted by the shopper:prune-carts command:

php artisan shopper:prune-carts
php artisan shopper:prune-carts --days=7

By default, carts that haven't been updated in the last 30 days (configurable via prune_after_days) are deleted, with or without lines, and their lines go with them. --days overrides the setting for one run. Only carts where completed_at is null are pruned. Completed carts are kept as historical records tied to their orders.

Shopper does not schedule the command. Schedule it in your routes/console.php:

use Illuminate\Support\Facades\Schedule;

Schedule::command('shopper:prune-carts')->daily();

Storefront Implementation

This section shows how to build a complete cart experience in your storefront. The examples are based on the patterns used in the Shopper demo store. They use App\Models\Product and App\Models\ProductVariant, the store's own models that extend Shopper's (see Extending the Model).

Cart Session Helper

A common pattern is to create a cartSession() helper that handles cart creation with the correct zone and channel. This avoids repeating the creation logic across your controllers and components:

// app/helpers.php

use Shopper\Cart\CartSessionManager;
use Shopper\Cart\Models\Cart;
use Shopper\Core\Models\Channel;

function cartSession(): Cart
{
    $session = resolve(CartSessionManager::class);
    $cart = $session->current();

    if (! $cart) {
        $defaultChannel = Channel::query()->scopes('default')->first();

        $cart = $session->create([
            'currency_code' => shopper_currency(),
            'channel_id' => $defaultChannel?->id,
            'zone_id' => session('zone_id'),
            'customer_id' => auth()->id(),
        ]);
    }

    return $cart;
}

Register the helper in your composer.json:

{
    "autoload": {
        "files": ["app/helpers.php"]
    }
}

Associating Cart on Login

When a guest adds items to their cart and then logs in, the cart should be associated with their account. Register a listener for the Login event in your AppServiceProvider:

use Illuminate\Auth\Events\Login;
use Illuminate\Support\Facades\Event;
use Shopper\Cart\CartSessionManager;

public function boot(): void
{
    Event::listen(Login::class, function (Login $event): void {
        resolve(CartSessionManager::class)->associate($event->user);
    });
}

Add to Cart Action

Create a dedicated action class that handles adding both products and variants to the cart:

namespace App\Actions\Cart;

use App\Models\Product;
use App\Models\ProductVariant;
use Shopper\Cart\CartManager;
use Shopper\Cart\Models\CartLine;

final readonly class AddToCart
{
    public function __construct(
        private CartManager $cartManager,
    ) {}

    public function handle(Product $product, ?ProductVariant $variant = null): CartLine
    {
        $purchasable = $variant ?? $product;

        return $this->cartManager->add(cartSession(), $purchasable);
    }
}

Livewire Cart Component

Here is a complete Livewire component for displaying and managing the cart as a slide-over panel:

namespace App\Livewire;

use App\Models\ProductVariant;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Livewire\Attributes\On;
use Livewire\Component;
use Shopper\Cart\CartManager;
use Shopper\Cart\CartSessionManager;
use Shopper\Cart\Models\CartLine;

final class ShoppingCart extends Component
{
    public int|float $subtotal = 0;

    /** @var Collection<int, CartLine> */
    public Collection $items;

    public function mount(): void
    {
        $this->loadCart();
    }

    #[On('cartUpdated')]
    public function loadCart(): void
    {
        $cart = resolve(CartSessionManager::class)->current();

        if (! $cart) {
            $this->items = collect();
            $this->subtotal = 0;

            return;
        }

        $cart->load('lines.purchasable');
        $cart->lines->loadMorph('purchasable', [
            ProductVariant::class => ['product'],
        ]);

        $this->items = $cart->lines;

        $context = resolve(CartManager::class)->calculate($cart);
        $this->subtotal = $context->subtotal;
    }

    public function removeFromCart(int $lineId): void
    {
        resolve(CartManager::class)->remove(cartSession(), $lineId);

        $this->loadCart();
        $this->dispatch('cartUpdated');
    }

    public function render(): View
    {
        return view('livewire.shopping-cart');
    }
}

The corresponding Blade view displays each cart line with its product details and a remove button:

<div>
    @if ($items->isEmpty())
        <p>Your cart is empty.</p>
    @else
        <ul>
            @foreach ($items as $line)
                <li class="flex items-center justify-between py-4">
                    <div>
                        <p class="font-medium">
                            @if ($line->purchasable instanceof \App\Models\ProductVariant)
                                {{ $line->purchasable->product->name }} - {{ $line->purchasable->name }}
                            @else
                                {{ $line->purchasable->name }}
                            @endif
                        </p>
                        <p class="text-sm text-gray-500">
                            Qty: {{ $line->quantity }}
                            &middot;
                            {{ shopper_money_format($line->unit_price_amount, cartSession()->currency_code) }}
                        </p>
                    </div>
                    <button wire:click="removeFromCart({{ $line->id }})">Remove</button>
                </li>
            @endforeach
        </ul>

        <div class="border-t pt-4">
            <p class="font-medium">
                Subtotal: {{ shopper_money_format($subtotal, cartSession()->currency_code) }}
            </p>
        </div>
    @endif
</div>

Cart Header Button

A small component that displays the cart item count in the navigation. It listens for the cartUpdated event to refresh automatically:

namespace App\Livewire;

use Illuminate\Contracts\View\View;
use Livewire\Attributes\On;
use Livewire\Component;
use Shopper\Cart\CartSessionManager;

final class ShoppingCartButton extends Component
{
    public int $count = 0;

    public function mount(): void
    {
        $this->updateCount();
    }

    #[On('cartUpdated')]
    public function updateCount(): void
    {
        $cart = resolve(CartSessionManager::class)->current();

        $this->count = $cart ? $cart->lines->sum('quantity') : 0;
    }

    public function render(): View
    {
        return view('livewire.shopping-cart-button');
    }
}

Displaying Cart Totals

Use the CartManager::calculate() method to get the full breakdown. The returned CartPipelineContext contains all computed values:

use Shopper\Cart\CartManager;

$context = resolve(CartManager::class)->calculate($cart);
<div>
    <p>Subtotal: {{ shopper_money_format($context->subtotal, $cart->currency_code) }}</p>

    @if ($context->discountTotal > 0)
        <p>Discount: -{{ shopper_money_format($context->discountTotal, $cart->currency_code) }}</p>
    @endif

    @if ($context->taxTotal > 0)
        <p>Tax: {{ shopper_money_format($context->taxTotal, $cart->currency_code) }}</p>
    @endif

    <p class="font-bold">Total: {{ shopper_money_format($context->total, $cart->currency_code) }}</p>
</div>

Applying a Coupon

Apply a discount code to the cart, then validate it. applyCoupon() only checks that the code exists. The other rules run when calculate() runs the pipeline, which skips an invalid discount without an error, so run the DiscountValidator to tell the customer why a code does not apply:

use Shopper\Cart\CartManager;
use Shopper\Cart\Discounts\DiscountValidator;
use Shopper\Cart\Exceptions\InvalidDiscountException;
use Shopper\Core\Models\Discount;

$manager = resolve(CartManager::class);

try {
    $manager->applyCoupon($cart, $couponCode);
} catch (InvalidDiscountException $e) {
    return back()->with('error', $e->getMessage());
}

$context = $manager->calculate($cart);
$discount = Discount::query()->where('code', $couponCode)->firstOrFail();

$result = resolve(DiscountValidator::class)->validate($discount, $context);

if (! $result->valid) {
    $manager->removeCoupon($cart);

    return back()->with('error', $result->failureReason);
}

Setting Checkout Addresses

Add shipping and billing addresses to the cart before converting to an order:

use Shopper\Cart\CartManager;
use Shopper\Core\Enum\AddressType;

$manager = resolve(CartManager::class);

$manager->addAddress($cart, AddressType::Shipping, [
    'first_name' => $request->first_name,
    'last_name' => $request->last_name,
    'address_1' => $request->address,
    'city' => $request->city,
    'postal_code' => $request->postal_code,
    'country_id' => $request->country_id,
]);

$manager->addAddress($cart, AddressType::Billing, $billingData);

Converting to Order

When the customer completes checkout, convert the cart into an order. The action runs inside a database transaction, calculates final totals, creates order records, and marks the cart as completed. If a discount limit is hit at commit time, catch DiscountLimitReachedException and surface a friendly message:

use Shopper\Cart\Actions\CreateOrderFromCartAction;
use Shopper\Cart\Exceptions\DiscountLimitReachedException;
use Shopper\Cart\Facades\Cart;

try {
    $order = resolve(CreateOrderFromCartAction::class)->execute(Cart::current());
} catch (DiscountLimitReachedException $e) {
    return back()->with('error', 'This discount can no longer be used.');
}

Cart::forget();

After converting the cart to an order, call Cart::forget() to clear the session. The cart is marked as completed and cannot be modified, but the session should be cleaned up so Cart::current() returns null. See the Payments page for processing the order payment.

Last updated on

Edit on GitHub