PHPackages                             mohammadmehrabani/conditional-coupon - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mohammadmehrabani/conditional-coupon

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mohammadmehrabani/conditional-coupon
====================================

The conditional coupon for the Laravel.

v1.1.0(7mo ago)341MITPHPPHP ^8.0

Since Oct 2Pushed 7mo agoCompare

[ Source](https://github.com/MohammadMehrabani/conditional-coupon)[ Packagist](https://packagist.org/packages/mohammadmehrabani/conditional-coupon)[ Docs](https://github.com/mohammadmehrabani/conditional-coupon)[ RSS](/packages/mohammadmehrabani-conditional-coupon/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (7)Versions (4)Used By (0)

conditional coupon code
=======================

[](#conditional-coupon-code)

With this package, you can add both simple and conditional discount coupon features to your application. You can develop your own custom conditions, which will be automatically checked when a discount coupon is applied. If a condition is violated, an error will be returned and the coupon will not be allowed to be used by the user.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require mohammadmehrabani/conditional-coupon
```

You can publish and run the migrations with:

```
php artisan vendor:publish --tag="conditional-coupon-migrations"
php artisan migrate
```

You can publish the config file with:

```
php artisan vendor:publish --tag="conditional-coupon-config"
```

This is the contents of the published config file:

```
return [
    'conditions' => [
        // Add custom check condition classes Implemented \MohammadMehrabani\ConditionalCoupon\CheckConditionAbstract
        // for example:
        // \App\CheckUsageLimitCondition::class => 'Usage limit',
        // \App\CheckPaymentTypesCondition::class => 'Payment type restriction',
        // \App\CheckPaymentMethodsCondition::class => 'Payment method restriction',
    ]
];
```

If you want any conditions to be checked when applying a discount coupon, simply create a class that implements `\MohammadMehrabani\ConditionalCoupon\CheckConditionAbstract` and add it to the `conditional-coupon.php` config file along with a title for the condition. No further action is needed—it's that simple.

```
namespace App;

use App\Models\Order;
use MohammadMehrabani\ConditionalCoupon\CheckConditionAbstract;
use MohammadMehrabani\ConditionalCoupon\Exceptions\CouponException;

class CheckUsageLimitCondition extends CheckConditionAbstract
{
    /**
     * @throws CouponException|\Exception
     */
    public function handle(mixed $payload, \Closure $next): mixed
    {
        $orderCount = Order::where([ // only for example
            'coupon_id' => $this->coupon->id,
            'user_id'   => auth()->id(),
            'status'    => 'fulfilled',
        ])->count();

        if ($orderCount > $this->condition->data) {
            throw new \Exception(__('Coupon user usage limit reached.'), 400);
        }

        return $next($payload);
    }
}

class CheckPaymentTypesCondition extends CheckConditionAbstract
{
    public function handle(mixed $payload, \Closure $next): mixed
    {
        if (empty(array_intersect($this->condition->data, ['cash', 'credit']))) {
            throw new \Exception('payment types do not match.');
        }

        return $next($payload);
    }
}
```

add to config file:

```
return [
    'conditions' => [
        \App\CheckUsageLimitCondition::class   => 'Usage limit',
        \App\CheckPaymentTypesCondition::class => 'Payment type restriction',
    ]
];
```

Usage
-----

[](#usage)

Implementing the CRUD for discount coupons—and adding conditions if needed—is up to you. Once created, you can simply use the discount coupon feature for your orders as shown in the example below.

### Listing Available Check Classes

[](#listing-available-check-classes)

You can retrieve all available Check classes using the `GetCustomConditions` class. Each Check class has a `title` property which is wrapped in `__()` for translation. This list can be used to populate the select box when creating discount coupons.

```
use MohammadMehrabani\ConditionalCoupon\GetCustomConditions;

GetCustomConditions::handle();
```

### create coupon with conditions

[](#create-coupon-with-conditions)

```
use MohammadMehrabani\ConditionalCoupon\Models\Coupon;
use MohammadMehrabani\ConditionalCoupon\Models\CouponCondition;

$coupon = Coupon::create([
    'code' => 'AMZ100',
    // fill other columns
]);

$couponCondition = CouponCondition::create([
    'coupon_id' => $coupon->id,
    'condition' => \App\CheckUsageLimitCondition::class,
    'data' => 1
]);

$couponCondition = CouponCondition::create([
    'coupon_id' => $coupon->id,
    'condition' => \App\CheckPaymentTypesCondition::class,
    'data' => ["credit", "cash"],
]);
```

### create coupon without conditions

[](#create-coupon-without-conditions)

```
use MohammadMehrabani\ConditionalCoupon\Models\Coupon;
use MohammadMehrabani\ConditionalCoupon\Models\CouponCondition;

$coupon = Coupon::create([
    'code' => 'AMZ100',
    // fill other columns
]);
```

### use coupon for order

[](#use-coupon-for-order)

```
use Illuminate\Support\Facades\DB;
use App\Models\Order;
use MohammadMehrabani\ConditionalCoupon\InquiryCoupon;

DB::transaction(function () {
    $inquiryCoupon = new InquiryCoupon();
    [
        $currency,
        $amount,
        $discountAmount,
        $payableAmount,
        $coupon
    ] = $inquiryCoupon->handle(code: request()->get('coupon_code'), amount: 1000000, locked: true);

   $order = Order::create([ // only for example
        'discount'  => $discountAmount,
        'amount'    => $payableAmount,
        'user_id'   => auth()->id(),
        'status'    => 'initial',
        'coupon_id' => $coupon->id,
        # Other fields as needed:
        // 'coupon_code'         => $coupon->code,
        // 'discount_percentage' => $coupon->discount_percentage,
        // 'discount_amount'     => $coupon->discount_amount,
    ]);

    $coupon->increment('used_count');
});
```

Discount Logic
--------------

[](#discount-logic)

The package supports two types of discount fields:

- `discount_percentage`
- `discount_amount`

### Rules

[](#rules)

1. **Single Field Case**

    - If only one of the fields is provided, the discount will be applied based on that field.
2. **Both Fields Case**

    - If both `discount_percentage` and `discount_amount` are provided:
        - The discount value is first calculated from the `discount_percentage`.
        - If the calculated percentage discount is **greater than** the fixed `discount_amount`, then the **fixed amount** will be applied.
        - If the calculated percentage discount is **less than or equal to** the fixed `discount_amount`, then the **percentage-based discount** will be applied.

### Example

[](#example)

- Order total: **$200**
- `discount_percentage`: **20%**
- `discount_amount`: **$30**

Calculation:

- 20% of $200 = $40
- Since $40 (percentage) &gt; $30 (amount), the final discount will be **$30**.

Testing
-------

[](#testing)

```
composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Mohammad Hossein Mehrabani](https://github.com/mohammadmehrabani)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance65

Regular maintenance activity

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

3

Last Release

215d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0fa1b376afd47d6a62883b6efd8179000cc4facc1547719e91d3e98d2bccc454?d=identicon)[MohammadMehrabani](/maintainers/MohammadMehrabani)

---

Top Contributors

[![MohammadMehrabani](https://avatars.githubusercontent.com/u/18621426?v=4)](https://github.com/MohammadMehrabani "MohammadMehrabani (8 commits)")

---

Tags

laravelcoupondiscountpromopromo codecoupon codediscount codemohammadmehrabaniconditional-couponconditional coupon codeconditional discount codeconditional-discountconditional promo codeconditional-promo

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/mohammadmehrabani-conditional-coupon/health.svg)

```
[![Health](https://phpackages.com/badges/mohammadmehrabani-conditional-coupon/health.svg)](https://phpackages.com/packages/mohammadmehrabani-conditional-coupon)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M686](/packages/barryvdh-laravel-ide-helper)[yajra/laravel-datatables-oracle

jQuery DataTables API for Laravel

4.9k33.8M338](/packages/yajra-laravel-datatables-oracle)[spatie/laravel-enum

Laravel Enum support

3655.4M31](/packages/spatie-laravel-enum)[psalm/plugin-laravel

Psalm plugin for Laravel

3274.9M308](/packages/psalm-plugin-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[laracraft-tech/laravel-useful-additions

A collection of useful Laravel additions!

58109.4k](/packages/laracraft-tech-laravel-useful-additions)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
