pixellair/laravel-discount-system

v1.0.0 2025-06-16 10:11 UTC

This package is not auto-updated.

Last update: 2025-06-16 16:37:01 UTC


README

A reusable, Composer-installable coupon-based discount system for Laravel projects.

Easily integrates into any Laravel app to provide:

  • ๐ŸŽฏ Percentage or fixed amount discounts
  • โณ Time-limited discounts
  • ๐Ÿ”‚ One-time use or limited usage
  • ๐Ÿ‘ค Per-user restrictions (only once per user)
  • ๐Ÿ‘ฅ Coupons for specific users only
  • ๐Ÿ’ต Minimum order amount validation
  • ๐Ÿง  Smart code generation with type prefixes

๐Ÿš€ Installation

1. Require via Composer

composer require pixellair/laravel-discount-system

2. Publish and Run Migrations

To create the necessary tables for storing discounts and their usage:

php artisan vendor:publish --tag=laravel-discount-system-migrations
php artisan migrate

๐Ÿ”ง Setup (If Needed)

If you're using Laravel 8+ with package auto-discovery, no setup is needed.

If not, register the service provider manually in config/app.php:

'providers' => [
    DiscountSystem\DiscountSystemServiceProvider::class,
],

###โš™๏ธ Usage Apply a Coupon to an Order

use DiscountSystem\Services\DiscountService;

$service = new DiscountService();

$result = $service->apply($couponCode, $userId, $orderAmount);

$discountAmount = $result['amount'];
$discount = $result['discount'];

Record a Usage After Applying

$service->recordUsage($discount, $userId);

๐Ÿงช Validations Performed in apply()

โœ… Coupon exists

โณ Coupon is active (start & end time)

๐Ÿ”‚ Usage limit not exceeded

๐Ÿ‘ค Coupon not already used by this user (if once_per_user)

๐Ÿ‘ฅ User is in allowed list (if specific_user_ids set)

๐Ÿ’ต Order meets min_order_amount requirement

If any condition fails, a ValidationException is thrown with a meaningful message.

๐Ÿงพ Code Generation Generate a prefixed coupon code for any type:

$code = $discountService->generateCode('T'); // e.g., T7K92LA

The prefix lets you categorize discounts (e.g., T for time-limited, A for amount-based).

๐Ÿ’ก Example Controller Usage

use DiscountSystem\Services\DiscountService;

public function applyCoupon(Request $request)
{
    $service = new DiscountService();

    try {
        $result = $service->apply($request->code, auth()->id(), $order->total);

        $order->discount_amount = $result['amount'];
        $order->save();

        $service->recordUsage($result['discount'], auth()->id());

        return response()->json(['success' => true, 'discount' => $result['amount']]);
    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json(['error' => $e->getMessage()], 422);
    }
}