PHPackages                             shamarkellman/flex-cart - 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. shamarkellman/flex-cart

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

shamarkellman/flex-cart
=======================

A flexible shopping cart package for Laravel 12

v1.0.1(3mo ago)021[2 PRs](https://github.com/ShamarKellman/flex-cart/pulls)MITPHPPHP ^8.3CI passing

Since Mar 13Pushed 2mo agoCompare

[ Source](https://github.com/ShamarKellman/flex-cart)[ Packagist](https://packagist.org/packages/shamarkellman/flex-cart)[ Docs](https://github.com/shamarkellman/flex-cart)[ GitHub Sponsors](https://github.com/ShamarKellman)[ RSS](/packages/shamarkellman-flex-cart/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (2)Dependencies (16)Versions (6)Used By (0)

FlexCart - A Flexible Shopping Cart Package for Laravel 12+
===========================================================

[](#flexcart---a-flexible-shopping-cart-package-for-laravel-12)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6cc73368b7d1b9ae399710514dec5a2eb0324866a47aa8255d9af7500412df90/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7368616d61726b656c6c6d616e2f666c65782d636172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/shamarkellman/flex-cart)[![GitHub Tests Action Status](https://camo.githubusercontent.com/b8ae583e67495ee479bb28e11c7e4613fe35995598fbc19fd1f08288a41b1712/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7368616d61726b656c6c6d616e2f666c65782d636172742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/shamarkellman/flex-cart/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/52ec2ffbffe07c2206ee6c783611f8456904c746e77adfa577f8292e8f51039c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7368616d61726b656c6c6d616e2f666c65782d636172742f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/shamarkellman/flex-cart/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/891d8345f67d1eccd73e3a560b6adf54c0a04509df723b9c8c075ab5278ccb60/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7368616d61726b656c6c6d616e2f666c65782d636172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/shamarkellman/flex-cart)

FlexCart is a flexible shopping cart package for Laravel 12+ that provides comprehensive cart functionality including multiple storage backends, tax calculations, shipping management, coupon/discounts, and Money PHP integration.

Features
--------

[](#features)

- Multiple storage backends (session and database)
- Flexible coupon/discount system with multiple discount types
- Tax calculations with configurable rates
- Shipping address and cost management
- Comprehensive event system for cart lifecycle hooks
- Money PHP integration for accurate financial calculations
- Custom exception handling with detailed error messages

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

[](#installation)

You can install the package via composer:

```
composer require shamarkellman/flex-cart
```

You can publish and run the migrations with:

```
php artisan vendor:publish --tag="flex-cart-migrations"
php artisan migrate
```

You can publish the config file with:

```
php artisan vendor:publish --tag="flex-cart-config"
```

Usage
-----

[](#usage)

### Basic Cart Operations

[](#basic-cart-operations)

```
use ShamarKellman\FlexCart\Facades\FlexCart;
use Money\Money;
use Money\Currency;

// Add product to cart
$product = Product::find(1);
$cartItem = FlexCart::addItem($product, 2);

// Add item with options (e.g., size, color)
$cartItemWithOptions = FlexCart::addItem($product, 1, [
    'size' => 'large',
    'color' => 'blue'
]);

// Update quantity
FlexCart::updateItem($cartItem->id, 3);

// Remove specific item
FlexCart::removeItem($cartItem->id);

// Clear entire cart
FlexCart::clear();
```

### Cart Information

[](#cart-information)

```
// Get all cart items
$items = FlexCart::items();

// Get specific item
$item = FlexCart::getItem($itemId);

// Count total items (sum of quantities)
$totalItems = FlexCart::count();

// Check if cart is empty
$isEmpty = FlexCart::isEmpty();

// Get cart totals
$subtotal = FlexCart::subtotal();      // Money object
$tax = FlexCart::tax();                // Money object
$shipping = FlexCart::shippingCost();  // Money object
$total = FlexCart::total();            // Money object

// Get raw amounts
echo $total->getAmount();              // '10000' (in cents)
echo $total->getCurrency()->getCode(); // 'USD'
```

### Coupon System

[](#coupon-system)

FlexCart includes a comprehensive coupon/discount system supporting multiple discount types.

#### Adding Coupons

[](#adding-coupons)

```
use ShamarKellman\FlexCart\Facades\FlexCart;
use ShamarKellman\FlexCart\Models\Coupon;

// Add a coupon to cart
$coupon = Coupon::where('code', 'SAVE20')->first();
$result = FlexCart::addCoupon($coupon);

// Check if coupon was added successfully
if ($result) {
    echo "Coupon applied!";
}

// Check if cart has a specific coupon
$hasCoupon = FlexCart::hasCoupon('SAVE20');

// Get coupon details
$coupon = FlexCart::getCoupon('SAVE20');
```

#### Removing Coupons

[](#removing-coupons)

```
// Remove a specific coupon
FlexCart::removeCoupon('SAVE20');

// Clear all coupons
FlexCart::clearCoupons();
```

#### Getting Discounts

[](#getting-discounts)

```
// Get general discount (products)
$generalDiscount = FlexCart::generalDiscount();

// Get shipping discount
$shippingDiscount = FlexCart::shippingDiscount();

// Get total discount
$totalDiscount = FlexCart::totalDiscount();

// Get subtotal after discounts
$subtotalWithCoupons = FlexCart::subtotalWithCoupons();

// Get final total (subtotal + shipping - discounts)
$total = FlexCart::total();
```

### Coupon Model

[](#coupon-model)

Create coupons in your database using the CouponFactory:

```
use ShamarKellman\FlexCart\Models\Coupon;

// Fixed amount coupon ($20 off)
$coupon = Coupon::factory()->fixedAmount(20)->create([
    'code' => 'SAVE20',
    'is_stackable' => true,
]);

// Percentage coupon (10% off)
$coupon = Coupon::factory()->percentage(10)->create([
    'code' => 'PERCENT10',
    'is_stackable' => false,
]);

// Free shipping coupon
$coupon = Coupon::factory()->shipping(0)->create([
    'code' => 'FREESHIP',
]);

// Coupon with restrictions
$coupon = Coupon::factory()
    ->withMinimumAmount(50)      // $50 minimum
    ->withUsageLimit(100)        // 100 uses max
    ->expiresInDays(30)          // Expires in 30 days
    ->create([
        'code' => 'SPECIAL',
    ]);
```

#### Coupon Types

[](#coupon-types)

TypeDescriptionValue Format`TYPE_FIXED_AMOUNT`Fixed discount on order totalAmount in cents`TYPE_PERCENTAGE`Percentage off order totalPercentage (0-100)`TYPE_SHIPPING`Free or discounted shippingAmount in cents#### Coupon Features

[](#coupon-features)

- **Stackable coupons**: Allow multiple coupons to be applied
- **Usage limits**: Limit total number of uses
- **Minimum amount**: Require minimum order total
- **Product-specific**: Apply to specific products only
- **Exclusions**: Exclude specific products from discount
- **Expiration**: Set expiration dates
- **Activation dates**: Set when coupon becomes active

#### Coupon Events

[](#coupon-events)

```
use ShamarKellman\FlexCart\Events\CouponApplied;
use ShamarKellman\FlexCart\Events\CouponRemoved;
use ShamarKellman\FlexCart\Events\CouponExpired;

Event::listen(CouponApplied::class, function ($event) {
    $coupon = $event->getCoupon();
    logger()->info('Coupon applied', ['code' => $coupon->getCode()]);
});

Event::listen(CouponRemoved::class, function ($event) {
    $coupon = $event->getCoupon();
    logger()->info('Coupon removed', ['code' => $coupon->getCode()]);
});

Event::listen(CouponExpired::class, function ($event) {
    $coupon = $event->getCoupon();
    logger()->info('Coupon expired', ['code' => $coupon->getCode()]);
});
```

### Shipping Management

[](#shipping-management)

```
// Set shipping address
FlexCart::setShippingAddress([
    'first_name' => 'John',
    'last_name' => 'Doe',
    'company' => 'Acme Corp', // optional
    'address_line_1' => '123 Main St',
    'address_line_2' => 'Apt 4B', // optional
    'city' => 'New York',
    'state' => 'NY',
    'postal_code' => '10001',
    'country' => 'US',
    'phone' => '+1-555-0123', // optional
    'email' => 'john@example.com', // optional
]);

// Set shipping cost
FlexCart::setShippingCost(new Money(1000, new Currency('USD'))); // $10.00

// Get shipping details
$shippingDetail = FlexCart::getShippingDetail();
echo $shippingDetail->first_name; // 'John'
echo $shippingDetail->country; // 'US'
```

### Cart Item Operations

[](#cart-item-operations)

```
$cartItem = FlexCart::addItem($product, 2);

// Get item details
$quantity = $cartItem->getQuantity();
$unitPrice = $cartItem->getUnitPrice();
$totalPrice = $cartItem->getTotal();
$taxAmount = $cartItem->getTaxAmount();
$options = $cartItem->getOptions();
$buyableProduct = $cartItem->getBuyable();

// Modify item directly
$cartItem->setQuantity(5);
$cartItem->setOptions(['size' => 'XL', 'gift_wrap' => true]);
```

### Working with Different Currencies

[](#working-with-different-currencies)

```
// Set default currency in config/flex-cart.php
'default_currency' => 'EUR',

// Or change currency dynamically
FlexCart::setShippingCost(new Money(1000, new Currency('EUR')));
```

### Advanced Usage Examples

[](#advanced-usage-examples)

```
// Check if item exists before adding
if (!FlexCart::getItem($productId)) {
    FlexCart::addItem($product, 1);
}

// Add multiple items at once
$products = [
    ['product' => $product1, 'quantity' => 2, 'options' => ['size' => 'M']],
    ['product' => $product2, 'quantity' => 1, 'options' => ['color' => 'red']],
];

foreach ($products as $item) {
    FlexCart::addItem($item['product'], $item['quantity'], $item['options'] ?? []);
}

// Calculate totals with tax (if tax rate is configured)
$subtotal = FlexCart::subtotal();
$taxRate = config('flex-cart.tax_rate', 0);
$totalWithTax = FlexCart::total();

// Format money for display
$formatter = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
echo $formatter->formatCurrency($total->getAmount() / 100, $total->getCurrency()->getCode());
// Output: $100.00
```

Configuration
-------------

[](#configuration)

### Environment Variables

[](#environment-variables)

```
# .env file
CART_DEFAULT_CURRENCY=USD
CART_TAX_RATE=8.25
CART_STORAGE_DRIVER=session
```

### Configuration File

[](#configuration-file)

After publishing the config file (`config/flex-cart.php`):

```
