Skip to content

Discounts

Complete reference for the Discount model, types, conditions, and usage in Shopper.

Discounts allow you to create promotional offers for your customers. Shopper supports percentage and fixed amount discounts with flexible application rules, eligibility conditions, and usage limits.

Models

Shopper uses two models to manage discounts:

ModelPurpose
Shopper\Core\Models\DiscountThe discount definition (code, type, value, rules)
Shopper\Core\Models\DiscountDetailPolymorphic link connecting discounts to specific products or customers

The Discount model implements Shopper\Core\Models\Contracts\Discount and the DiscountDetail model implements Shopper\Core\Models\Contracts\DiscountDetail. Neither model is configurable via config/shopper/models.php.

Each discount also has a computed status attribute that returns a Shopper\Core\Enum\DiscountStatus case. The first matching rule wins:

StatusDatabase ValueWhen
DraftdraftThe discount is not saved yet
Disableddisabledis_active is false
Expiredexpiredend_at is in the past
LimitReachedlimit_reachedtotal_use has reached usage_limit
Scheduledscheduledstart_at is in the future
ActiveactiveNone of the above
use Shopper\Core\Enum\DiscountStatus;

if ($discount->status === DiscountStatus::Active) {
    // The code can be offered to customers
}

Database Schema

Discount Table

The table is discounts, prefixed with config('shopper.core.table_prefix') (sh_ by default).

ColumnTypeNullableDefaultDescription
idbigintnoautoPrimary key
codestringno-Unique discount code
typestringno-Discount type enum
valueintegerno-Discount value (percentage or cents)
is_activebooleannofalseWhether the code can be used
apply_tostringno-Application scope enum
min_requiredstringno-Requirement type enum
min_required_valuestringyesnullMinimum value required
eligibilitystringno-Eligibility type enum
usage_limitunsigned integeryesnullMaximum total uses (null = unlimited)
usage_limit_per_userbooleannofalseLimit one use per customer
total_useunsigned integerno0Current total usage count
start_atdatetimeno-Discount start date
end_atdatetimeyesnullDiscount end date (null = no expiry)
zone_idbigintyesnullFK to zone (null = all zones), set to null when the zone is deleted
metadatajsonbyesnullAdditional custom data (cast to array)
created_attimestampyesnullCreation timestamp
updated_attimestampyesnullLast update timestamp

Discountable Table (Pivot)

The table is discountables, with the same prefix.

ColumnTypeNullableDescription
idbigintnoPrimary key
conditionstringyesCondition type (apply_to, eligibility)
total_useunsigned integernoDefault 0. Shopper does not increment it: the per-user limit counts orders instead
discountable_idbigintnoPolymorphic relation ID
discountable_typestringnoPolymorphic relation type
discount_idbigintnoFK to discount, deleted with the discount
created_attimestampyesCreation timestamp
updated_attimestampyesLast update timestamp

Discount Type

The DiscountType enum defines value types:

use Shopper\Core\Enum\DiscountType;

DiscountType::Percentage   // percentage - e.g., 10% off
DiscountType::FixedAmount  // fixed_amount - e.g., $10 off
TypeDatabase ValueValue Handling
PercentagepercentageStored as-is (10 = 10%)
Fixed Amountfixed_amountStored in cents (1000 = $10.00), or in whole units for a zero-decimal currency

Discount Application

The DiscountApplyTo enum defines where the discount applies:

use Shopper\Core\Enum\DiscountApplyTo;

DiscountApplyTo::Order     // order - Applies to entire order
DiscountApplyTo::Products  // products - Applies to specific products
ScopeDatabase ValueDescription
OrderorderDiscount applies to every cart line
ProductsproductsDiscount applies only to lines of linked products. A variant line matches when its parent product is linked

Discount Eligibility

The DiscountEligibility enum defines who can use the discount:

use Shopper\Core\Enum\DiscountEligibility;

DiscountEligibility::Everyone   // everyone - All customers
DiscountEligibility::Customers  // customers - Specific customers only
EligibilityDatabase ValueDescription
EveryoneeveryoneAny customer can use, guests included
CustomerscustomersOnly linked customers can use. The cart must belong to a logged-in customer

Discount Requirements

The DiscountRequirement enum defines minimum conditions:

use Shopper\Core\Enum\DiscountRequirement;

DiscountRequirement::None     // none - No minimum
DiscountRequirement::Price    // price - Minimum order amount
DiscountRequirement::Quantity // quantity - Minimum items count
RequirementDatabase Valuemin_required_value
NonenoneNot used
PricepriceMinimum cart subtotal in cents (unit price times quantity for each line, before the discount)
QuantityquantityMinimum number of items (sum of the cart line quantities)

Discount Condition

The DiscountCondition enum is used on the DiscountDetail pivot model to distinguish whether a linked record represents a product (the discount applies to) or a customer (who is eligible):

use Shopper\Core\Enum\DiscountCondition;

DiscountCondition::ApplyTo      // apply_to - Links a product to the discount
DiscountCondition::Eligibility  // eligibility - Links a customer to the discount

Relationships

Items (DiscountDetail)

Store the same discountable_type values as the admin panel: config('shopper.models.product') for products and config('auth.providers.users.model') for customers. The cart only accepts a customer link whose type matches config('auth.providers.users.model').

use Shopper\Core\Enum\DiscountCondition;

// Get all discount items (products or customers)
$discount->items; // Collection of DiscountDetail models

// Add a product to discount
$discount->items()->create([
    'condition' => DiscountCondition::ApplyTo,
    'discountable_type' => config('shopper.models.product'),
    'discountable_id' => $productId,
]);

// Add eligible customer
$discount->items()->create([
    'condition' => DiscountCondition::Eligibility,
    'discountable_type' => config('auth.providers.users.model'),
    'discountable_id' => $userId,
]);

Zone

// Get discount zone (market)
$discount->zone; // Zone model or null

// Restrict discount to a zone
$discount->update(['zone_id' => $zoneId]);

Value Handling

Fixed amount values are stored in cents. Percentage values are stored as the percentage number.

For a $10 fixed discount, store 1000 (cents). For a 15% percentage discount, store 15:

use Shopper\Core\Enum\DiscountType;

$discount->update([
    'type' => DiscountType::FixedAmount,
    'value' => 1000, // 1000 cents = $10.00
]);

$discount->update([
    'type' => DiscountType::Percentage,
    'value' => 15, // 15%
]);

Saving a discount throws Shopper\Core\Exceptions\InvalidDiscountValueException when value is 0 or less, or when a percentage is above 100.

A percentage is applied to each applicable line and rounded to the cent. A fixed amount is capped at the subtotal of the applicable lines and split across them in proportion to their subtotal. The cart applies the stored amount as-is, without currency conversion: the admin form reads it in the currency of the discount's zone, or in the store currency when no zone is set.

Usage Limit Enforcement

Discounts can cap the total number of redemptions with usage_limit and restrict each customer to one redemption with usage_limit_per_user. Both limits are enforced with strong consistency guarantees so that a coupon can never be silently over-redeemed under concurrent checkout.

Global Usage Limit

The usage_limit column caps the total number of redemptions across all customers. The total_use counter is incremented atomically inside the CreateOrderFromCartAction transaction:

  1. The discount row is locked with lockForUpdate to serialize concurrent checkouts.
  2. A conditional UPDATE increments total_use only if it is still below usage_limit.
  3. If the conditional update affects zero rows, the limit was exhausted between cart validation and commit. DiscountLimitReachedException::global() is thrown and the order transaction rolls back, so no order is created.

This compare-and-swap check was added in v2.8. If you upgrade from an older release, follow the v2.7 to v2.8 upgrade guide.

Per-User Limit

When usage_limit_per_user is true, each customer can redeem the discount at most once. The check counts prior orders on the orders.discount_id column (introduced in v2.8), not the legacy DiscountDetail.total_use counter:

config('shopper.models.order')::query()
    ->where('discount_id', $discount->id)
    ->where('customer_id', $cart->customer_id)
    ->exists();

The same query runs in two places. DiscountValidator runs it each time the cart is calculated, so a customer who already used the code sees the cart total without the discount before checkout. CreateOrderFromCartAction re-checks at commit and throws DiscountLimitReachedException::perUser() if the customer redeemed it in the meantime.

A per-user limit needs an identified customer, so a guest cart (no customer_id) can never apply a discount that sets usage_limit_per_user. DiscountValidator skips the discount with the discount.requires_login reason, and CreateOrderFromCartAction throws DiscountLimitReachedException::perUser().

Helpers

$discount->hasReachedLimit();

if ($discount->usage_limit !== null) {
    $remaining = $discount->usage_limit - $discount->total_use;
}

Handling DiscountLimitReachedException

Wrap your checkout flow to surface a friendly message to the customer when either limit is hit at commit time:

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.');
}

The exception has two static constructors that match the two limit types:

ConstructorThrown When
DiscountLimitReachedException::global($code)Global usage_limit was reached between cart validation and order commit
DiscountLimitReachedException::perUser($code)Customer already redeemed a discount with usage_limit_per_user set, or a guest cart uses such a discount

Creating Discounts

Percentage Discount for All Orders

use Shopper\Core\Models\Discount;
use Shopper\Core\Enum\DiscountType;
use Shopper\Core\Enum\DiscountApplyTo;
use Shopper\Core\Enum\DiscountEligibility;
use Shopper\Core\Enum\DiscountRequirement;

$discount = Discount::query()->create([
    'code' => 'SUMMER20',
    'type' => DiscountType::Percentage,
    'value' => 20, // 20% off
    'is_active' => true,
    'apply_to' => DiscountApplyTo::Order,
    'eligibility' => DiscountEligibility::Everyone,
    'min_required' => DiscountRequirement::None,
    'start_at' => now(),
    'end_at' => now()->addMonth(),
]);

Fixed Amount Discount with Minimum Order

$discount = Discount::query()->create([
    'code' => 'SAVE10',
    'type' => DiscountType::FixedAmount,
    'value' => 1000, // 1000 cents = $10 off
    'is_active' => true,
    'apply_to' => DiscountApplyTo::Order,
    'eligibility' => DiscountEligibility::Everyone,
    'min_required' => DiscountRequirement::Price,
    'min_required_value' => '5000', // Minimum 5000 cents = $50 order
    'start_at' => now(),
    'usage_limit' => 100, // Max 100 uses
]);

Product-Specific Discount

$discount = Discount::query()->create([
    'code' => 'PRODUCT15',
    'type' => DiscountType::Percentage,
    'value' => 15,
    'is_active' => true,
    'apply_to' => DiscountApplyTo::Products,
    'eligibility' => DiscountEligibility::Everyone,
    'min_required' => DiscountRequirement::None,
    'start_at' => now(),
]);

// Link specific products
$discount->items()->createMany([
    [
        'condition' => 'apply_to',
        'discountable_type' => config('shopper.models.product'),
        'discountable_id' => $product1->id,
    ],
    [
        'condition' => 'apply_to',
        'discountable_type' => config('shopper.models.product'),
        'discountable_id' => $product2->id,
    ],
]);

VIP Customer Discount

$discount = Discount::query()->create([
    'code' => 'VIP30',
    'type' => DiscountType::Percentage,
    'value' => 30,
    'is_active' => true,
    'apply_to' => DiscountApplyTo::Order,
    'eligibility' => DiscountEligibility::Customers,
    'min_required' => DiscountRequirement::None,
    'start_at' => now(),
    'usage_limit_per_user' => true, // One use per customer
]);

// Link eligible customers
foreach ($vipCustomers as $customer) {
    $discount->items()->create([
        'condition' => 'eligibility',
        'discountable_type' => config('auth.providers.users.model'),
        'discountable_id' => $customer->id,
    ]);
}

Retrieving Discounts

use Shopper\Core\Models\Discount;

// Get all active discounts
$discounts = Discount::query()
    ->where('is_active', true)
    ->where('start_at', '<=', now())
    ->where(function ($q) {
        $q->whereNull('end_at')
            ->orWhere('end_at', '>', now());
    })
    ->get();

// Get discount by code
$discount = Discount::query()
    ->where('code', 'SUMMER20')
    ->where('is_active', true)
    ->first();

// Get discounts for a zone
$discounts = Discount::query()
    ->where('is_active', true)
    ->where(function ($q) use ($zoneId) {
        $q->whereNull('zone_id')
            ->orWhere('zone_id', $zoneId);
    })
    ->get();

// Get discounts with available uses
$discounts = Discount::query()
    ->where('is_active', true)
    ->where(function ($q) {
        $q->whereNull('usage_limit')
            ->orWhereColumn('total_use', '<', 'usage_limit');
    })
    ->get();

Discount Validation

CartManager::applyCoupon() only checks that the code exists. The Cart package validates the discount each time the cart is calculated: Shopper\Cart\Discounts\DiscountValidator checks the active flag, the value, the date range, the usage limits, the eligibility, the zone and the minimum amount or quantity. You do not need to build these rules yourself.

A discount that fails a check is skipped: the cart total is calculated without it, no exception is thrown and the code stays on the cart. To tell the customer why, call DiscountValidator::validate() yourself. It returns a DiscountValidationResult with a valid boolean and a translated failureReason (see the Storefront Example).

For a quick check outside the cart, without a cart context:

use Shopper\Core\Models\Discount;

$discount = Discount::query()
    ->where('code', $code)
    ->where('is_active', true)
    ->first();

if ($discount && ! $discount->hasReachedLimit()) {
    // Active and has remaining uses. Dates, eligibility, zone and minimums are not checked here.
}

Configuration

Disabling Discounts

If your store doesn't use discount codes, disable the feature in config/shopper/features.php. This removes the Discounts page and its menu item from the admin panel. The cart does not read this flag: CartManager::applyCoupon() still accepts the codes already in the database.

use Shopper\Enum\FeatureState;

return [
    'discount' => FeatureState::Disabled,
];

Permissions

The admin panel generates five permissions for discount management:

PermissionDescription
browse_discountsView the discounts list and its menu item
read_discountsGenerated with the others, not checked by the 2.x admin panel
add_discountsCreate new discounts
edit_discountsEdit existing discounts
delete_discountsDelete discounts

Components

To customize the admin UI for discount management:

php artisan shopper:component:publish discount

Creates config/shopper/components/discount.php:

use Shopper\Livewire;

return [
    'pages' => [
        'discount-index' => Livewire\Pages\Discount\Index::class,
    ],
    'components' => [
        'slide-overs.discount-form' => Livewire\SlideOvers\DiscountForm::class,
    ],
];

Storefront Example

Applying a discount code on the storefront uses the Cart package API. The CartManager::applyCoupon() method validates the code exists, and the calculation pipeline handles the rest (validation rules, discount calculation, and adjustment creation). A code that exists but breaks a rule is still saved on the cart, so the example runs the validator and removes the code when it does not apply:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Shopper\Cart\CartManager;
use Shopper\Cart\Discounts\DiscountValidator;
use Shopper\Cart\Exceptions\InvalidDiscountException;
use Shopper\Cart\Facades\Cart;
use Shopper\Core\Models\Discount;

class CouponController extends Controller
{
    public function apply(Request $request)
    {
        $request->validate(['code' => 'required|string']);

        $manager = resolve(CartManager::class);
        $cart = Cart::current();

        if ($cart === null) {
            return back()->with('error', 'Your cart is empty.');
        }

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

        $discount = Discount::query()->where('code', $request->code)->first();
        $result = resolve(DiscountValidator::class)->validate($discount, $manager->calculate($cart));

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

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

        return back()->with('success', 'Discount applied.');
    }

    public function remove()
    {
        $cart = Cart::current();

        if ($cart === null) {
            return back();
        }

        resolve(CartManager::class)->removeCoupon($cart);

        return back()->with('success', 'Discount removed.');
    }
}

Use Cases

ScenarioTypeApply ToEligibilityRequirement
Site-wide salePercentageOrderEveryoneNone
$10 off orders over $50FixedOrderEveryonePrice
Buy 3+ get 10% offPercentageOrderEveryoneQuantity
VIP member exclusivePercentageOrderCustomersNone
Product clearancePercentageProductsEveryoneNone
Welcome code for selected customersFixedOrderCustomersNone

Last updated on

Edit on GitHub