data column.
Overview
ALunar\Core\Models\Discount record describes when a discount is active, who it is available to, and what it targets. The type column names a class implementing Lunar\Core\Contracts\DiscountType that decides how the discount is applied to a cart. Lunar ships three types: percentage off, fixed amount off, and buy-x-get-y.
redemption is cast to Lunar\Core\Enums\DiscountRedemptionMethod. DiscountRedemptionMethod::Automatic applies the discount to every eligible cart. DiscountRedemptionMethod::Coupon applies it only to a cart whose coupon code belongs to the discount.
Relationships
Scopes
The status attribute
Coupons: Coupon
A discount whoseredemption is coupon applies only to a cart with one of its codes. Each code is a Lunar\Core\Models\Coupon, with its own usage count and limit. A discount can have one shared code or many codes, for example one per recipient of an email campaign. Redeeming a code needs no signed-in user and no customer on the cart: the code is the credential.
A discount’s own
max_uses still caps the total across all its codes.
Relationships
Scopes
isUsable() makes the same check on a loaded coupon.
Creating a coupon discount
Lunar\Core\Contracts\Actions\Discounts\CreatesCoupon and Lunar\Core\Contracts\Actions\Discounts\DeletesCoupon do the same through the container, and are what the admin panel calls. Deleting a code keeps its redemptions with a null coupon_id.
redemption is set explicitly rather than derived from whether a discount has codes, so deleting the last code of a coupon discount does not turn it into an automatic discount that applies to every cart.
Generating codes
Discount::generateCoupons() creates a batch of codes on a discount and returns the batch ULID, which every code in the batch stores in its batch column. A Lunar\Core\DataObjects\CouponBatch describes the batch.
Both take the same named options:
A batch with no codes, such as
ofQuantity(0) or a list with no addresses, throws an InvalidArgumentException.
The batch ULID is set when the CouponBatch is created, and is available as $batch->id. Generating the same CouponBatch again completes the batch instead of adding codes to it, so a retried job does not make duplicates.
generateCoupons() delegates to Lunar\Core\Contracts\Actions\Discounts\GeneratesCoupons. The default action, Lunar\Core\Actions\Discounts\GenerateCoupons, inserts codes in chunks of 1,000 with insertOrIgnore() and keeps going until the batch is complete, so a code that collides with an existing one is replaced, not lost. If 10 chunks in a row insert nothing, the code space is nearly used up and it throws a RuntimeException; use a longer length. Codes are inserted in bulk, so no Eloquent model events fire for them.
Code generator
Each code comes fromLunar\Core\Contracts\CouponCodeGenerator, which has one method, generate(CouponBatch $batch): string. The default, Lunar\Core\Generators\CouponCodeGenerator, returns the prefix followed by length characters from an alphabet of uppercase letters and digits without the look-alike characters 0, O, 1, I and L. The generator does not need to return unique codes: the action replaces any that collide. Bind a different implementation in a service provider to change the format:
Queueing large batches
Lunar\Core\Jobs\GenerateCouponsJob generates a batch on the queue. It carries the CouponBatch, so a retry completes the same batch.
lunar.discounts.coupons.queue_threshold codes (default 5000), and dispatches GenerateCouponsJob for a larger one. Code that calls generateCoupons() directly decides for itself. Measured locally against tables already holding 200,000 codes, 5,000 codes take about 0.1 to 0.2 seconds on SQLite, MySQL 8 and PostgreSQL, and 50,000 take 1 to 2.3 seconds. The time grows with the number of codes, not with the size of the table, and is spent almost entirely in the database inserts.
Exporting codes
The admin panel exports a discount’s codes, or one batch, as CSV with the columnscode, email, uses and redeemed_at (the most recent redemption). In code, read a batch from the coupons relationship:
App\Mail\SpringCampaign stands for the store’s own mailable.
Resolving a cart’s code
Lunar\Core\Models\Cart::coupon() is a BelongsTo from the cart’s coupon_code to coupons.code. Both columns are stored uppercase, so the relationship is a single indexed lookup and can be eager loaded. Everything that matches a cart’s code reads it through $cart->coupon:
Discounts::getDiscounts()loads automatic discounts, plus the discount$cart->couponbelongs to.AbstractDiscountType::checkDiscountConditions()passes a coupon discount only when$cart->couponbelongs to it and is usable.Discounts::validateCoupon()checks that the code exists, is usable, and belongs to an active, usable discount.
coupon_code on a cart unloads its coupon relationship, so the next read resolves the new code.
When an order is created, Lunar\Core\Pipelines\Order\Creation\MapDiscountBreakdown adds coupon_id and coupon_code to each discount_breakdown entry that came from a coupon discount. The code is copied, so the order still shows it after the coupon is deleted.
Usage: DiscountRedemption
Lunar counts a use of a discount when an order is placed, not when its draft order is created. A draft order is not a sale: a declined card or an abandoned checkout uses nothing, and a shopper who retries on the same cart, or on a new one, still gets the discount.Lunar\Core\Listeners\RecordDiscountRedemptions handles Lunar\Core\Events\Orders\OrderPlaced. For each discount in the order’s discount_breakdown, it records a DiscountRedemption and increments the discount’s uses, and the coupon’s uses for a coupon discount, each in a single database update. An order records each discount once, so the event firing again for the same order counts nothing.
A unique index on
discount_id and order_id keeps one row per discount per order.
Relationships
Per-customer limits
max_uses_per_user limits how many times one customer can use a discount. It applies to guests as well as signed-in customers. Lunar identifies the customer by user when there is one, and by email otherwise, and counts the redemptions that match either. A customer who has used a discount as a guest can’t use it again by signing in, and a signed-in customer can’t use it again by signing out, as long as the email is the same.
Lunar\Core\Contracts\Actions\Discounts\ResolvesCustomerEmail (default Lunar\Core\Actions\Discounts\ResolveCustomerEmail) decides which email identifies a cart’s customer. It returns the first of:
- the signed-in user’s email;
- the billing address
contact_email; - the shipping address
contact_email.
contact_email is used only when the billing address has none. The result is lower-cased and trimmed. To match emails more strictly, for example by ignoring +tags, bind your own implementation of the contract in a service provider.
Lunar\Core\Contracts\Actions\Discounts\CountsCustomerRedemptions (default Lunar\Core\Actions\Discounts\CountCustomerRedemptions) counts a discount’s redemptions whose user_id is the cart’s user or whose email is the resolved email. It returns 0 when the cart has neither.
The limit is enforced in three places:
- Discount conditions. Each cart calculation drops the discount once the customer’s count reaches
max_uses_per_user. A guest cart with no email yet keeps the discount, and drops it as soon as an email that has used it is added. - Coupon validation.
Discounts::validateCoupon()rejects a coupon the cart’s customer has used up. See Validating coupons. - Order creation.
Lunar\Core\Validation\Cart\ValidateCustomerForDiscountsruns in theOrderCreateValidationstep list. It fails when a discount withmax_uses_per_useris applied to the cart and the cart has neither a user nor an email, so$cart->canCreateOrder()returnsfalseuntil the customer gives one.
uses does. Lunar does not give a use back when an order is cancelled.
Going over a limit
Eligibility is checked on every cart calculation, so a discount at itsmax_uses no longer applies to new carts. Two carts priced with the last use can still both be paid for before either order is placed, and the same customer can pay for two carts at once. When a placement takes the discount’s uses above its max_uses, the coupon’s uses above its max_uses, or the customer’s redemptions above max_uses_per_user, the listener keeps the order, because it has already been paid for, and reports it:
- It dispatches
Lunar\Core\Events\Discounts\DiscountLimitExceeded, with publicorder,discount,limitandcouponproperties.limitis aLunar\Core\Enums\DiscountLimit:DiscountLimit::MaxUsesfor the discount-wide limit,DiscountLimit::CouponMaxUsesfor the coupon’s own limit, orDiscountLimit::MaxUsesPerUserfor the per-customer limit.couponis theLunar\Core\Models\Couponthe order used, ornullfor an automatic discount. - It logs an activity on the order with the event
discount-limit-exceededand the propertiesdiscount_id,discount(the discount name),coupon(the code, ornull),limit(max_uses,coupon_max_usesormax_uses_per_user),uses(the count that went over) andmax_uses(the value of that limit).
Targeting: Discountable
Lunar\Core\Models\Discountable links a product, product variant, or collection to a discount, tagged with a role via its type column.
condition: must be in the cart for the discount to activate (used by buy-x-get-y for the “buy” side).exclusion: excluded from a percentage-off or fixed-amount-off discount’s eligible lines.limitation: a percentage-off or fixed-amount-off discount only applies to these products or variants.reward: given as the reward by a buy-x-get-y discount.
Relationships
Scopes
Percentage-off and fixed-amount-off discounts also target lines by collection or brand directly through the
Discount::collections() and Discount::brands() relationships (pivot type of limitation or exclusion), rather than through Discountable.
Built-in discount types
Every discount type extendsLunar\Core\DiscountTypes\AbstractDiscountType and implements Lunar\Core\Contracts\DiscountType:
AbstractDiscountType provides shared behavior every type relies on:
checkDiscountConditions(Cart $cart): bool: validates the discount against the cart before it applies anything, including, for a coupon discount, that$cart->couponbelongs to it and is usable, the cart customer againstcustomers()(if restricted), adata.min_pricesminimum spend for the cart’s currency,max_uses, andmax_uses_per_user(counted from the user’s redemptions). Every shipped type calls this at the top ofapply().addDiscountBreakdown(Cart $cart, DiscountBreakdown $breakdown): records how much this discount took off, and which lines it affected, on$cart->discountBreakdown.
data.min_prices is keyed by currency code and stored in minor units, and applies regardless of which type is used:
PercentageOff
FixedAmountOff
PercentageOff and FixedAmountOff both narrow the cart’s eligible lines through Lunar\Core\DiscountTypes\Concerns\TargetsCartLines, which applies the discount’s collection, brand, and Discountable limitations and exclusions before any amount is calculated.
Prior to v2, this was a single
AmountOff type switched by a data.fixed_value boolean. Every stored discount of that type is migrated by the upgrade package to either PercentageOff or FixedAmountOff, and data.fixed_values is renamed to data.amounts.BuyXGetY
discountableConditions, reward products (the “get” side) from discountableRewards. Both accept products, product variants, or collections.
Condition and reward matching also accepts collections: a
Discountable entry with discountable_type set to a collection matches any cart line whose product belongs to that collection.
Automatically adding rewards
Whenautomatically_add_rewards is true and a qualifying cart does not already contain enough reward items, BuyXGetY adds a cart line for the reward rather than requiring the customer to add it themselves. A line the discount added always holds exactly the reward units the cart earns in the current calculation:
- Reward units go first to reward lines the customer added, cheapest first. When the reward product is already on a line the customer added, that line is discounted and its
added_by_discount_idstaysnull. - Units left over go onto lines the discount manages, in this order: its existing added lines keep up to their current quantity, oldest first; units still left raise those lines as far as stock allows; any remaining units go on a new line.
- A new line’s reward is chosen at random from the fulfillable
discountableRewards(a collection reward picks a random fulfillable product from that collection). An out-of-stock reward is skipped rather than raising an error, and a reward quantity greater than one goes on a single line, not one line per unit. - A line
BuyXGetYadds hasadded_by_discount_idset to the discount’s ID, andisAddedByDiscount()returnstrue. - When the cart earns fewer units, the added line’s quantity is lowered. When the cart no longer earns the reward at all (the condition items are removed, the discount ends or reaches its usage limit, its coupon is removed, or
automatically_add_rewardsis turned off), the line is deleted on the next calculation. - Added lines are not the customer’s purchases. They never count toward any discount’s conditions, minimum spend or targeted lines, so a reward cannot keep itself earned.
- The customer cannot change an added line’s quantity:
Cart::updateLine()throws aLunar\Core\Exceptions\Carts\CartExceptionwhen the quantity differs. A meta-only update at the same quantity is accepted. The customer can remove an added line, but it returns on the next calculation while the cart still earns it. - A product the customer adds never merges into a line added by a discount:
Cart::add()creates a separate line. Merging carts keeps the two apart as well, and order creation copiesadded_by_discount_idto the order line. - When the discount is deleted, the lines it added are deleted from every cart without a completed order. Carts with a completed order keep the lines, with
added_by_discount_idset tonull.
Lunar\Core\Contracts\Actions\Discounts\ReconcilesRewardLines after the CartCalculation steps run. When it changes any line, the steps run once more so shipping and tax see the cart as it now stands. See Extending Carts.
The Discounts facade
Lunar\Core\Facades\Discounts resolves Lunar\Core\Contracts\DiscountManager (bound scoped, so a long-lived worker gets a fresh instance per request or job):
getDiscounts() and apply() memoize the resolved discount list per cart state (cart ID, coupon code, customer, and line purchasables). Call resetDiscounts() after a change that should re-evaluate eligibility, for example after a coupon code is applied to the cart.
Registering a custom discount type
boot() method. See Extending Discounts for how to build a custom discount type.
Validating coupons
Lunar\Core\Validation\CouponValidator, checks that the code is under its own max_uses and belongs to an active discount under its max_uses and, if the discount sets max_uses_per_user, that the cart’s customer has not reached it, counted through CountsCustomerRedemptions (see Per-customer limits). Without a cart argument it checks the cart from CartSession::current(). A guest whose cart has no email yet passes, because there is nobody to count against. Validate the coupon again once the customer gives an email; see Re-validating a coupon once the email is known.
Bind a different implementation of Lunar\Core\Contracts\CouponValidator in your own service provider to customize this. The contract’s signature is validate(string $coupon, ?Cart $cart = null): bool.
How discounts apply in the cart pipeline
Eligibility is narrowed in two stages. First,getDiscounts() pre-filters candidate discounts at the database level: when a cart is given, only discounts whose Discountable entries (condition or limitation) match the cart’s products or variants, or whose collections()/brands() pivot type is condition and matches a collection or brand on a cart line, are loaded at all. Second, each loaded discount’s own apply() re-checks the full set of conditions (checkDiscountConditions()) and, for PercentageOff/FixedAmountOff, narrows to eligible lines via TargetsCartLines (limitation/exclusion on collections, brands, and Discountable entries).
Discounts are applied as one step in the cart calculation step list (Lunar\Core\Enums\StepList::CartCalculation), after lines and shipping are calculated and before tax:
Lunar\Core\Pipelines\Cart\ApplyDiscounts resets $cart->discounts and $cart->discountBreakdown, then calls Discounts::apply($cart), which runs each eligible discount’s type in turn. Each type mutates the affected CartLine totals (discountTotal, subTotalDiscounted) directly and, if it applied, records a Lunar\Core\ValueObjects\Cart\DiscountBreakdown describing what happened:
Because tax is calculated after discounts, discount amounts reduce the tax-relevant subtotal for the affected lines.
Custom discount types
A custom discount type extendsLunar\Core\DiscountTypes\AbstractDiscountType:
DiscountBreakdown, and register the type.