laravel-couponables icon indicating copy to clipboard operation
laravel-couponables copied to clipboard

Coupons/promocodes leveraging Eloquent's polymorphic relationships

Laravel Couponables

Laravel Couponables

Latest Version on Packagist Total Downloads Code Quality Code Coverage GitHub Tests Action Status PHPStan

This package provides polymorphic coupon functionality for your Laravel application.

The package requires PHP ^8.x and Laravel ^8.71 or ^9.0.


#StandWithUkraine

SWUbanner


Installation

Install the package using composer:

composer require michael-rubel/laravel-couponables

Publish the migrations:

php artisan vendor:publish --tag="couponables-migrations"

Publish the config file:

php artisan vendor:publish --tag="couponables-config"

Usage

After publishing migrations, apply a trait in the model you want to use as a $redeemer:

use HasCoupons;

Artisan command

You can add coupons to your database using Artisan command:

php artisan make:coupon YourCouponCode

Optionally, you can pass the next arguments:

'--value'         // The 'value' to perform calculations based on the coupon provided
'--type'          // The 'type' to point out calculation strategy
'--limit'         // Limit how many times the coupon can be applied by the model
'--quantity'      // Limit how many coupons are available overall (this value will decrement)
'--expires_at'    // Set expiration time for the coupon
'--redeemer_type' // Polymorphic model type. Can as well be morph-mapped value, i.e. 'users'
'--redeemer_id'   // Redeemer model ID
'--data'          // JSON column to store any metadata you want for this particular coupon

Adding coupons using model

You can as well add coupons simply using model:

Coupon::create([
    'code'  => '...',
    'value' => '...',
    ...
]);

Basic operations

Verify the coupon code:

$redeemer->verifyCoupon($code);

Redeem the coupon:

$redeemer->redeemCoupon($code);

Redeem the coupon in context of another model:

$redeemer
  ->redeemCoupon($code)
  ->for($course);

Combined redeemCoupon and for behavior (assuming the $course includes HasCoupons trait):

$course->redeemBy($redeemer, $code);

If something's going wrong, methods verifyCoupon and redeemCoupon will throw an exception:

CouponExpiredException      // Coupon is expired (`expires_at` column).
InvalidCouponException      // Coupon is not found in the database.
NotAllowedToRedeemException // Coupon is assigned to the specific model (`redeemer` morphs).
OverLimitException          // Coupon is over the limit for the specific model (`limit` column).
OverQuantityException       // Coupon is exhausted (`quantity` column).
CouponException             // Generic exception for all cases.

If you want to bypass the exception and do something else:

$redeemer->verifyCouponOr($code, function ($exception) {
    // Your action with $exception!
});
$redeemer->redeemCouponOr($code, function ($exception) {
    // Your action with $exception!
});

Redeemer checks

Check if this coupon is already used by the model:

$redeemer->isCouponAlreadyUsed($code);

Check if the coupon is over the limit for the model:

$redeemer->isCouponOverLimit($code);

Coupon checks

public function isExpired(): bool;
public function isNotExpired(): bool;
public function isDisposable(): bool;
public function isOverQuantity(): bool;
public function isRedeemedBy(Model $redeemer): bool;
public function isOverLimitFor(Model $redeemer): bool;

This method references the model assigned to redeem the coupon:

public function redeemer(): ?Model;

Listeners

If you go event-driven, you can handle package events:


Generators

Seeding records with random codes

app(CouponServiceContract::class)->generateCoupons(times: 10, length: 7);
  • Note: This will only fill the code column.

Adding coupons to redeem only by specified model

app(CouponServiceContract::class)->generateCouponFor($redeemer, 'my-test-code', [
  // here you can pass parameters from the list above
]);

Extending package functionality

Traits DefinesColumns and DefinesPivotColumns contain the methods that define column names to use by the package. You can use a method binding to override the package's method behavior.

Example method binding in your ServiceProvider:

bind(CouponContract::class)->method('getCodeColumn', fn () => 'coupon')
// This method returns the `coupon` column name instead of `code` from now.

Alternatively, you can extend/override the entire class using config values or container bindings. All the classes in the package have their own contract (interface), so you're free to modify it as you wish.

CouponService has the Macroable trait, so you can inject the methods to interact with the service without overriding anything.

For example:

CouponService::macro('getCouponUsing', function (string $column, string $value) {
    return $this->model
        ->where($column, $value)
        ->first();
});

call(CouponService::class)->getCouponUsing('type', 'macro')

Contributing

If you see any ways we can improve the package, PRs are welcomed. But remember to write tests for your use cases.

Testing

composer test