1. Go to this page and download the library: Download binafy/laravel-discount library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
binafy / laravel-discount example snippets
use Binafy\LaravelDiscount\Enums\DiscountType;
Schema::table('discounts', function (Blueprint $table) {
$table->enum('type', DiscountType::values())->default(DiscountType::Percentage->value)->change();
$table->decimal('value', 10, 2)->default(0)->change();
});
use Binafy\LaravelDiscount\Enums\DiscountType;
use Binafy\LaravelDiscount\Models\Discount;
$discount = Discount::query()->create([
'name' => 'Summer Sale',
'type' => DiscountType::Percentage,
'value' => 20, // 20%
]);
$discount = Discount::query()->create([
'name' => 'Ten dollars off',
'type' => DiscountType::Fixed,
'value' => 10, // deducts 10 from the total
]);
LaravelDiscount::applyCode('EURO10', 50, $user, payload: ['currency' => 'EUR']); // OK
LaravelDiscount::applyCode('EURO10', 50, $user, payload: ['currency' => 'USD']);
// throws DiscountCurrencyMismatchException: "This discount is only available for orders in EUR."
// config/laravel-discount.php
'currency' => env('DISCOUNT_CURRENCY'), // e.g. DISCOUNT_CURRENCY=EUR
// 3 items at 100 each: the third one is free.
LaravelDiscount::apply($discount, 300, quantity: 3)->discountAmount; // 100.0
// 6 items at 50 each: two full sets, so two items are free.
LaravelDiscount::apply($discount, 300, quantity: 6)->discountAmount; // 100.0
// Below a full set, nothing applies.
LaravelDiscount::apply($discount, 200, quantity: 2)->discountAmount; // 0.0
// Buy 2, get the third at 50% off, at most 2 discounted items per order.
'conditions' => ['buy' => 2, 'get' => 1, 'get_discount_percentage' => 50, 'max_free_items' => 2],
use Binafy\LaravelDiscount\Traits\HasDiscounts;
class Product extends Model
{
use HasDiscounts;
}
// Attach and query
$product->discounts()->attach($discount);
$product->validDiscounts(); // only the currently applicable ones
$product->hasDiscount('TECH10'); // by code or by model instance
// Apply all attached valid discounts to a price (stacking rules
use Binafy\LaravelDiscount\Exceptions\DiscountConditionFailedException;
try {
$result = LaravelDiscount::applyCode($code, $total, $user, quantity: $count, payload: ['items' => $items]);
} catch (DiscountConditionFailedException $e) {
return back()->withErrors($e->getMessage()); // e.g. "This discount is only available on your first purchase."
}
'conditions' => ['rules' => [
['type' => 'first_purchase'],
// or override the model for this rule only:
['type' => 'first_purchase', 'model' => \App\Models\Subscription::class, 'column' => 'user_id'],
]],
// in a service provider
use Binafy\LaravelDiscount\Conditions\FirstPurchaseCondition;
use Binafy\LaravelDiscount\Support\DiscountContext;
FirstPurchaseCondition::countUsing(fn (DiscountContext $context) => Order::query()
->where('user_id', $context->userId())
->where('status', OrderStatus::Paid)
->count());
class CountPaidOrders
{
public function __invoke(DiscountContext $context): int
{
return Order::query()->where('user_id', $context->userId())->paid()->count();
}
}
use Binafy\LaravelDiscount\Contracts\DiscountCondition;
use Binafy\LaravelDiscount\Support\DiscountContext;
class WeekendOnlyCondition implements DiscountCondition
{
public function __construct(protected array $days = ['Saturday', 'Sunday']) {}
public static function fromArray(array $config): static
{
return new static($config['days'] ?? ['Saturday', 'Sunday']);
}
public function passes(DiscountContext $context): bool
{
return in_array(now()->englishDayOfWeek, $this->days);
}
public function message(): string
{
return 'This discount only runs at the weekend.';
}
}
// or at runtime, e.g. in a service provider
use Binafy\LaravelDiscount\Support\ConditionFactory;
ConditionFactory::register('weekend_only', WeekendOnlyCondition::class);
$context->discount; // the Discount being validated
$context->amount; // the order amount
$context->user; // the user model or id, may be null
$context->userId(); // the id, or null for a guest
$context->sessionId; // the guest session, may be null
$context->quantity; // how many items the amount covers
$context->items(); // Collection of the payload's items
$context->get('key'); // any other payload value, dot notation supported
$result = LaravelDiscount::applyMany([$tenPercent, $tenFixed, $bigSolo], 100);
$result->discounts; // the discounts that were actually applied
$result->discountAmount; // the winning total
use Binafy\LaravelDiscount\Rules\ValidDiscountCode;
public function rules(): array
{
return [
'code' => ['
use Binafy\LaravelDiscount\Exceptions\DiscountException;
use Binafy\LaravelDiscount\Exceptions\DiscountExpiredException;
try {
$result = LaravelDiscount::applyCode($code, $total, $user);
} catch (DiscountExpiredException $e) {
return back()->withErrors("Code {$e->getDiscount()->code} has expired.");
} catch (DiscountException $e) {
return back()->withErrors($e->getMessage());
}
use Binafy\LaravelDiscount\Events\DiscountRedeemed;
Event::listen(DiscountRedeemed::class, function (DiscountRedeemed $event) {
// $event->discount, $event->usage
});
use Binafy\LaravelDiscount\Integrations\LaravelCart\CartDiscount;
$cartDiscount = app(CartDiscount::class);
// Apply a code (or discount models) to the whole cart total
$result = $cartDiscount->applyToCart($cart, 'SUMMER-8FJ2K9QW');
$result->payableAmount();
// Apply a discount to a specific cart item (price × quantity)
$result = $cartDiscount->applyToItem($cartItem, $discount);
// Automatically apply the discounts attached to each item's model
// (via the HasDiscounts trait) across the whole cart
$result = $cartDiscount->applyItemDiscounts($cart);
$result = $cartDiscount->applyItemDiscounts($cart);
$result->hasFreeShipping(); // true when any item's discount grants it
$result->payableTotal(35); // the cart total plus the shipping still due