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:
| Model | Purpose |
|---|---|
Shopper\Core\Models\Discount | The discount definition (code, type, value, rules) |
Shopper\Core\Models\DiscountDetail | Polymorphic 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:
| Status | Database Value | When |
|---|---|---|
| Draft | draft | The discount is not saved yet |
| Disabled | disabled | is_active is false |
| Expired | expired | end_at is in the past |
| LimitReached | limit_reached | total_use has reached usage_limit |
| Scheduled | scheduled | start_at is in the future |
| Active | active | None 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).
| Column | Type | Nullable | Default | Description |
|---|---|---|---|---|
id | bigint | no | auto | Primary key |
code | string | no | - | Unique discount code |
type | string | no | - | Discount type enum |
value | integer | no | - | Discount value (percentage or cents) |
is_active | boolean | no | false | Whether the code can be used |
apply_to | string | no | - | Application scope enum |
min_required | string | no | - | Requirement type enum |
min_required_value | string | yes | null | Minimum value required |
eligibility | string | no | - | Eligibility type enum |
usage_limit | unsigned integer | yes | null | Maximum total uses (null = unlimited) |
usage_limit_per_user | boolean | no | false | Limit one use per customer |
total_use | unsigned integer | no | 0 | Current total usage count |
start_at | datetime | no | - | Discount start date |
end_at | datetime | yes | null | Discount end date (null = no expiry) |
zone_id | bigint | yes | null | FK to zone (null = all zones), set to null when the zone is deleted |
metadata | jsonb | yes | null | Additional custom data (cast to array) |
created_at | timestamp | yes | null | Creation timestamp |
updated_at | timestamp | yes | null | Last update timestamp |
Discountable Table (Pivot)
The table is discountables, with the same prefix.
| Column | Type | Nullable | Description |
|---|---|---|---|
id | bigint | no | Primary key |
condition | string | yes | Condition type (apply_to, eligibility) |
total_use | unsigned integer | no | Default 0. Shopper does not increment it: the per-user limit counts orders instead |
discountable_id | bigint | no | Polymorphic relation ID |
discountable_type | string | no | Polymorphic relation type |
discount_id | bigint | no | FK to discount, deleted with the discount |
created_at | timestamp | yes | Creation timestamp |
updated_at | timestamp | yes | Last 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| Type | Database Value | Value Handling |
|---|---|---|
| Percentage | percentage | Stored as-is (10 = 10%) |
| Fixed Amount | fixed_amount | Stored 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| Scope | Database Value | Description |
|---|---|---|
| Order | order | Discount applies to every cart line |
| Products | products | Discount 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| Eligibility | Database Value | Description |
|---|---|---|
| Everyone | everyone | Any customer can use, guests included |
| Customers | customers | Only 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| Requirement | Database Value | min_required_value |
|---|---|---|
| None | none | Not used |
| Price | price | Minimum cart subtotal in cents (unit price times quantity for each line, before the discount) |
| Quantity | quantity | Minimum 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 discountRelationships
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:
- The discount row is locked with
lockForUpdateto serialize concurrent checkouts. - A conditional
UPDATEincrementstotal_useonly if it is still belowusage_limit. - 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:
| Constructor | Thrown 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:
| Permission | Description |
|---|---|
browse_discounts | View the discounts list and its menu item |
read_discounts | Generated with the others, not checked by the 2.x admin panel |
add_discounts | Create new discounts |
edit_discounts | Edit existing discounts |
delete_discounts | Delete discounts |
Components
To customize the admin UI for discount management:
php artisan shopper:component:publish discountCreates 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
| Scenario | Type | Apply To | Eligibility | Requirement |
|---|---|---|---|---|
| Site-wide sale | Percentage | Order | Everyone | None |
| $10 off orders over $50 | Fixed | Order | Everyone | Price |
| Buy 3+ get 10% off | Percentage | Order | Everyone | Quantity |
| VIP member exclusive | Percentage | Order | Customers | None |
| Product clearance | Percentage | Products | Everyone | None |
| Welcome code for selected customers | Fixed | Order | Customers | None |
Last updated on
Edit on GitHub