PHP code example of daikazu / flexicart

1. Go to this page and download the library: Download daikazu/flexicart library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

daikazu / flexicart example snippets


use Daikazu\Flexicart\Facades\Cart;

// Add item as array
Cart::addItem([
    'id' => 1,
    'name' => 'Product Name',
    'price' => 29.99,
    'quantity' => 2,
    'attributes' => [
        'color' => 'red',
        'size' => 'large'
    ]
]);

// Add multiple items at once
Cart::addItem([
    [
        'id' => 2,
        'name' => 'Another Product',
        'price' => 15.50,
        'quantity' => 1
    ],
    [
        'id' => 3,
        'name' => 'Third Product',
        'price' => 45.00,
        'quantity' => 3
    ]
]);

// Update quantity
Cart::updateItem('item_id', ['quantity' => 5]);

// Update attributes
Cart::updateItem('item_id', [
    'attributes' => [
        'color' => 'blue',
        'size' => 'medium'
    ]
]);

// Update multiple properties
Cart::updateItem('item_id', [
    'quantity' => 3,
    'price' => 25.99,
    'attributes' => ['color' => 'green']
]);

// Remove a specific item
Cart::removeItem('item_id');

// Clear all items from the cart
Cart::clear();

// Get all items
$items = Cart::items();

// Get a specific item
$item = Cart::item('item_id');

// Get cart counts
$totalItems = Cart::count(); // Total quantity of all items
$uniqueItems = Cart::uniqueCount(); // Number of unique items

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

// Get cart totals
$subtotal = Cart::subtotal(); // Subtotal before conditions
$total = Cart::total(); // Final total after all conditions
$taxableSubtotal = Cart::getTaxableSubtotal(); // Subtotal of taxable items only

use Daikazu\Flexicart\Conditions\Types\PercentageCondition;
use Daikazu\Flexicart\Conditions\Types\FixedCondition;
use Daikazu\Flexicart\Enums\ConditionTarget;

// Add a 10% discount to the cart using condition class
$discount = new PercentageCondition(
    name: '10% Off Sale',
    value: -10, // Negative for discount
    target: ConditionTarget::SUBTOTAL
);
Cart::addCondition($discount);

// Add a $5 shipping fee using condition class
$shipping = new FixedCondition(
    name: 'Shipping Fee',
    value: 5.00,
    target: ConditionTarget::SUBTOTAL
);
Cart::addCondition($shipping);

// Add condition using array format with specific condition class
$memberDiscount = PercentageCondition::make([
    'name' => 'Member Discount',
    'value' => -15,
    'target' => ConditionTarget::SUBTOTAL
]);
Cart::addCondition($memberDiscount);

// Add condition to a specific item
$itemDiscount = new PercentageCondition(
    name: 'Item Discount',
    value: -20,
    target: ConditionTarget::ITEM
);
Cart::addItemCondition('item_id', $itemDiscount);

// Add multiple conditions at once
Cart::addConditions([
    new FixedCondition('Processing Fee', 2.50, ConditionTarget::SUBTOTAL),
    new PercentageCondition('Bulk Discount', -5, ConditionTarget::SUBTOTAL)
]);

// Remove a specific condition from the cart
Cart::removeCondition('10% Off Sale');

// Remove a condition from a specific item
Cart::removeItemCondition('item_id', 'Item Discount');

// Clear all cart conditions
Cart::clearConditions();

// Add non-taxable item
Cart::addItem([
    'id' => 4,
    'name' => 'Non-taxable Service',
    'price' => 100.00,
    'quantity' => 1,
    'taxable' => false
]);

// Update existing item to be non-taxable
Cart::updateItem('item_id', ['taxable' => false]);

// config/flexicart.php

// Use session storage (default)
'storage' => 'session',

// Use database storage
'storage' => 'database',

// Use custom storage class
'storage_class' => App\Services\CustomCartStorage::class,

'session_key' => 'my_custom_cart_key',

'currency' => 'USD', // ISO currency code
'locale' => 'en_US', // Locale for formatting

'cart_model' => App\Models\CustomCart::class,
'cart_item_model' => App\Models\CustomCartItem::class,

// Sequential calculation (each discount applies to the result of previous discounts)
'compound_discounts' => true,

// Parallel calculation (all discounts apply to the original price)
'compound_discounts' => false,

'cleanup' => [
    'enabled' => true,
    'lifetime' => 60 * 24 * 7, // 1 week in minutes
],

use Daikazu\Flexicart\Price;

// Create from numeric value
$price = Price::from(29.99);

// Create with specific currency
$price = Price::from(29.99, 'EUR');

// Create from Money object
$money = \Brick\Money\Money::of(29.99, 'USD');
$price = new Price($money);

$price1 = Price::from(10.00);
$price2 = Price::from(5.00);

// Addition
$total = $price1->plus($price2); // $15.00

// Subtraction
$difference = $price1->subtract($price2); // $5.00

// Multiplication
$doubled = $price1->multiplyBy(2); // $20.00

// Division
$half = $price1->divideBy(2); // $5.00

$price = Price::from(1234.56);

// Get formatted string
$formatted = $price->formatted(); // "$1,234.56"

// Get raw numeric value
$amount = $price->toFloat(); // 1234.56

// Get string representation
$string = (string) $price; // "$1,234.56"

// Get minor value (cents)
$cents = $price->getMinorValue(); // 123456

// Manually persist cart data
Cart::persist();

// Get raw cart data for custom storage
$cartData = Cart::getRawCartData();

// Get a specific cart
$cart = Cart::getCartById('user_123_cart');

// Switch to a different cart
$guestCart = Cart::getCartById('guest_cart');



namespace App\Cart\Conditions;

use Daikazu\Flexicart\Conditions\Condition;
use Daikazu\Flexicart\Enums\ConditionType;
use Daikazu\Flexicart\Price;

class BuyOneGetOneCondition extends Condition
{
    public ConditionType $type = ConditionType::PERCENTAGE;

    public function calculate(?Price $price = null): Price
    {
        // Custom calculation logic
        // For example, buy one get one 50% off
        if ($this->attributes->quantity >= 2) {
            $discount = $price->multipliedBy(0.5);
            return $discount->multipliedBy(-1); // Negative for discount
        }

        return Price::from(0);
    }

    public function formattedValue(): string
    {
        return 'Buy One Get One 50% Off';
    }
}



namespace App\Cart\Storage;

use Daikazu\Flexicart\Contracts\StorageInterface;

class RedisCartStorage implements StorageInterface
{
    public function get(string $key): array
    {
        // Implement Redis get logic
    }

    public function put(string $key, array $data): void
    {
        // Implement Redis put logic
    }

    public function forget(string $key): void
    {
        // Implement Redis forget logic
    }

    public function flush(): void
    {
        // Implement Redis flush logic
    }
}

'storage_class' => App\Cart\Storage\RedisCartStorage::class,

// In your AppServiceProvider or cart usage
config(['app.debug' => true]);
bash
php artisan vendor:publish --tag="flexicart-config"
bash
php artisan vendor:publish --tag="flexicart-migrations"
php artisan migrate
blade
{{-- resources/views/cart.blade.php --}}
@if(Cart::isEmpty())
    <p>Your cart is empty.</p>
@else
    <div class="cart">
        <h2>Shopping Cart</h2>

        <div class="cart-items">
            @foreach(Cart::items() as $item)
                <div class="cart-item">
                    <h4>{{ $item->name }}</h4>
                    <p>Price: {{ $item->unitPrice()->formatted() }}</p>
                    <p>Quantity: {{ $item->quantity }}</p>
                    <p>Subtotal: {{ $item->subtotal()->formatted() }}</p>

                    @if($item->attributes)
                        <div class="attributes">
                            @foreach($item->attributes as $key => $value)
                                <span class="attribute">{{ $key }}: {{ $value }}</span>
                            @endforeach
                        </div>
                    @endif

                    <form action="{{ route('cart.remove') }}" method="POST">
                        @csrf
                        <input type="hidden" name="item_id" value="{{ $item->id }}">
                        <button type="submit">Remove</button>
                    </form>
                </div>
            @endforeach
        </div>

        <div class="cart-totals">
            <p>Subtotal: {{ Cart::subtotal()->formatted() }}</p>
            <p><strong>Total: {{ Cart::total()->formatted() }}</strong></p>
        </div>

        <div class="cart-actions">
            <a href="{{ route('cart.clear') }}" class="btn btn-secondary">Clear Cart</a>
            <a href="{{ route('checkout') }}" class="btn btn-primary">Checkout</a>
        </div>
    </div>
@endif