An online store looks like a catalogue with a checkout attached. The code that keeps it honest is everything behind that: what is actually in stock, what the customer really owes, what state each order is in and what happens when a payment arrives late, twice, or not at all.

Those rules change constantly — a new delivery zone, a new discount, a second warehouse. A store stays maintainable when each rule lives in one place and the data model makes the wrong thing hard to do. These are the patterns that get it there.

The server is the only authority on money

A browser is a machine the customer controls. Anything it sends can be edited before it arrives. So the first rule of a checkout is that the client describes what is being bought and never how much it costs.

A request to place an order should look like this:

{
  "items": [
    { "product_id": 418, "quantity": 2 },
    { "product_id": 77, "quantity": 1 }
  ],
  "delivery_method_id": 3,
  "district_id": 12,
  "coupon_code": "WELCOME"
}

No prices, no subtotal, no delivery charge, no total. The server looks every figure up:

class OrderCalculator
{
    public function calculate(Collection $lines, DeliveryRule $delivery, ?Coupon $coupon): OrderTotals
    {
        $subtotal = $lines->sum(fn (CartLine $line) => $line->product->price * $line->quantity);

        $discount = $coupon?->discountFor($subtotal, $lines) ?? 0;
        $shipping = $delivery->chargeFor($lines, $subtotal - $discount);

        return new OrderTotals(
            subtotal: $subtotal,
            discount: $discount,
            shipping: $shipping,
            total: $subtotal - $discount + $shipping,
        );
    }
}

The same rule applies to the quieter endpoints. A delivery quote or a coupon check should take a basket, not a subtotal. If the endpoint accepts a subtotal, a hand-written request can supply whatever figure unlocks free delivery or a minimum-spend discount.

Store money as integers in the smallest unit — cents, paisa — or as decimals with fixed precision. Floating-point arithmetic and currency do not mix; 0.1 + 0.2 is the proof.

An order remembers its own prices

A product's price changes. An order placed last month must not.

Copy onto the order line everything needed to reproduce the sale exactly as it happened:

$order->items()->create([
    'product_id' => $product->id,
    'product_name' => $product->name,
    'sku' => $product->sku,
    'unit_price' => $product->price,
    'quantity' => $line->quantity,
    'line_total' => $product->price * $line->quantity,
]);

The foreign key lets you navigate to the current product. The copied columns are the historical record. An invoice regenerated a year later must show the name and price from the day of the sale, even if the product has since been renamed, repriced or deleted.

Stock is a ledger, not a number

The simplest stock model is a quantity column on the product. It answers "how many do we have?" and nothing else — not why the number is what it is, not who changed it, not whether last week's count was right.

A ledger records every change as a row:

Schema::create('inventory_movements', function (Blueprint $table) {
    $table->id();
    $table->foreignId('product_id')->constrained();
    $table->foreignId('location_id')->constrained('inventory_locations');
    $table->integer('quantity');            // positive in, negative out
    $table->string('reason');               // sale, purchase, return, adjustment, transfer
    $table->nullableMorphs('source');       // the order, purchase order or adjustment behind it
    $table->foreignId('user_id')->nullable()->constrained();
    $table->timestamps();
});

The current stock is the sum of the movements, usually kept in a summary table for speed and rebuilt from the ledger whenever it is in doubt. When a physical count disagrees with the system, there is a trail to read rather than a number to overwrite.

This is also what lets a website and a shop counter share stock. Both write movements against the same product; neither owns the figure.

Reserve stock inside a transaction

Two customers, one remaining copy, both pressing Place order in the same second. Without care, both orders succeed.

Lock the stock row while deciding:

DB::transaction(function () use ($product, $quantity, $order) {
    $stock = InventoryStock::where('product_id', $product->id)->lockForUpdate()->firstOrFail();

    if ($stock->available < $quantity) {
        throw new OutOfStockException($product);
    }

    $stock->decrement('available', $quantity);

    InventoryMovement::create([
        'product_id' => $product->id,
        'location_id' => $stock->location_id,
        'quantity' => -$quantity,
        'reason' => 'sale',
        'source_type' => Order::class,
        'source_id' => $order->id,
    ]);
});

lockForUpdate() makes the second transaction wait until the first has finished, at which point it sees the reduced figure and fails cleanly. Decide in advance what the customer sees in that case; "one of your items has just sold out" is better than a generic error.

Orders move through named states

An order is a small state machine. Writing the states and the allowed moves down — in code, not in people's heads — prevents a surprising number of bugs.

From May move to
Pending Confirmed, Cancelled
Confirmed Processing, Cancelled
Processing Shipped, Cancelled
Shipped Delivered, Returned
Delivered Returned
enum OrderStatus: string
{
    case Pending = 'pending';
    case Confirmed = 'confirmed';
    case Processing = 'processing';
    case Shipped = 'shipped';
    case Delivered = 'delivered';
    case Cancelled = 'cancelled';
    case Returned = 'returned';

    public function canMoveTo(self $next): bool
    {
        return in_array($next, match ($this) {
            self::Pending => [self::Confirmed, self::Cancelled],
            self::Confirmed => [self::Processing, self::Cancelled],
            self::Processing => [self::Shipped, self::Cancelled],
            self::Shipped => [self::Delivered, self::Returned],
            self::Delivered => [self::Returned],
            default => [],
        }, true);
    }
}

Every change of status goes through one method that checks the move, records it in a history table with who and when, and triggers whatever follows — releasing stock on cancellation, notifying the customer on shipment. Nobody writes $order->status = 'shipped' directly.

The history table is not bureaucracy. "Where is my order?" is the most common question a shop receives, and the history answers it.

Placing an order must be safe to repeat

A customer presses the button, the connection drops, and they press it again. Or the page is refreshed. Or two tabs are open. Without protection, each attempt is a new order.

Give each checkout attempt a key, generated once in the browser and sent with every retry:

$key = $request->header('Idempotency-Key');

$existing = IdempotencyKey::where('key', $key)->first();
if ($existing) {
    return response()->json($existing->response, $existing->status);
}

$order = $placeOrder->handle($request->validated());

IdempotencyKey::create(['key' => $key, 'response' => $payload, 'status' => 201]);

A repeated key returns the original order instead of creating another. Put a unique index on the key column so that two simultaneous requests cannot both pass the check.

Payments arrive on their own schedule

A payment gateway tells you the outcome twice: once by redirecting the customer back to your site, and once by calling a webhook on your server. Only the second can be trusted. The customer may close the browser before the redirect; the redirect's parameters can be tampered with.

Treat the webhook as the source of truth:

  • Verify the signature before reading the body.
  • Record the event with the gateway's own event ID, under a unique index, so a redelivered webhook is recognised and ignored.
  • Compare the amount the gateway reports with the order total. A successful payment for the wrong amount is not a paid order.
  • Answer quickly and do the real work in a queued job. Gateways retry slow endpoints, which produces the duplicates you were trying to avoid.

Let the return page say "we are confirming your payment" and read the order's actual status, rather than deciding anything itself.

Let guests buy

Requiring an account at the last step is a reliable way to lose a sale. Let a customer check out with a name, a phone number or email and an address, and offer an account afterwards.

A guest still needs to find their order. Authorise the lookup by something only they know about it — the order number together with the phone number or email it was placed with — rather than by the order number alone, which is easy to guess if it is sequential.

Keep the rules where you can change them

Delivery charges, tax rates and discount conditions change more often than code is deployed. Store them as data — a table of delivery rules by zone and method, a table of coupons with their conditions — and let the calculator read them. A new delivery zone should be a row someone adds in an admin panel, not a release.

The opposite holds for the shape of the rules. How a discount combines with a delivery charge is logic; it belongs in code, in one class, with tests around it.

What this buys

Each of these patterns is small. Together they give a store three properties that are hard to add later:

  • Every figure can be explained. A total is a calculation from stored inputs; a stock level is a sum of movements; a status is the last entry in a history.
  • Every operation can be repeated safely. A retried checkout, a redelivered webhook and a double-clicked button all end in the same state as a single attempt.
  • Every rule has one home. Changing how delivery is priced means opening one class or editing one table.

That is what maintainable means for a system that handles other people's money: when something looks wrong, you can find out why, and when a rule changes, you know where to go.