pixellair / laravel-discount-system
Laravel discount system
Requires
- php: ^8.0
- illuminate/database: ^9.0|^10.0
- illuminate/support: ^9.0|^10.0
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); } }