joelwmale/laravel-cart 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

joelwmale/laravel-cart

最新稳定版本:1.2.1

Composer 安装命令:

composer require joelwmale/laravel-cart

包简介

A cart implementation for Laravel

README 文档

README

Laravel Cart Latest Version on Packagist GitHub Tests Action Status Total Downloads GitHub last commit License Free

A Cart Implementation for Laravel.

Supported Laravel Versions: 10, 11, and 12.

For Laravel 9.0 and below, please use version 1.0

Table of Contents

???? Getting Started

???? Installing

Install the package through Composer.

composer require joelwmale/laravel-cart

????‍???? Demo

// Add an item to the cart
\Cart::add(
    1, // any unique id
    'Product 1', // product name
    19.99, // product price
    2, // quantity
    ['size' => 'large'] // an array of extra attributes
);

// get the entire cart
$cartContents = \Cart::getContent();

// update an item already in the cart
\Cart::update(
    1, // the same unique id that was used to add the item
    ['quantity' => 3] // the quantity to update
);

// remove the item by its id
\Cart::remove(1);

// get the total of the cart
$total = Cart::getTotal();

// clear it all when you've finished (like when you've stored the order)
\Cart::clear();

???? Documentation

⚙️ Configuration

You can publish the configuration file to customize various options.

php artisan vendor:publish --provider="Joelwmale\Cart\CartServiceProvider" --tag="config"

Formatting Numbers

The package by default does not use round to format numbers, and instead returns the number using floatval().

If you'd prefer this number to be rounded, you can customize the formatting in the configuration file.

Defaults to false.

'format_numbers' => env('LARAVEL_CART_FORMAT_VALUES', false),
'round_mode' => env('LARAVEL_CART_ROUND_MODE', 'down'),

Decimals

You can customize the number of decimals in the configuration file.

Defaults to 2.

'decimals' => env('LARAVEL_CART_DECIMALS', 2),

Round Mode

The package uses the round function to round the prices. You can customize the rounding mode in the configuration file.

Defaults to down.

'round_mode' => env('LARAVEL_CART_ROUND_MODE', 'down'),

Basic Usage

The cart has a default sessionKey that holds the cart data and stores it in the session, so you can have multiple carts for multiple users.

This also serves as a cart unique identifier which you can use to bind a cart to a specific user if you want to.

Make sure to call \Cart::setSessionKey($sessionKey) before calling any other cart methods.

Usually this is not required.

// Binds the cart to a unique id (user id, session id, etc.)
\Cart::setSessionKey(User::first()->id);

Adding to the cart: Cart::add()

There are a few ways to add items to the cart.

// Add a simple product to the cart
Cart::add(
    455, # product id
    'Sample Item', # product name
    100.99, # product price
    2, # quantity
    [] # optional attributes
);

// array format
Cart::add([
    456, # product id
    'Leather Shoes', # product name
    187, # product price
    1, # quantity
    [] # optional attributes
]);


// add an item with attributes
Cart::add([
    457, // product id
    'T-Shirt', // product name
    29.99, // product price
    1, // quantity
    [
        'size' => 'L',
        'color' => 'Blue'
    ] // attributes
]);

// add an item with conditions
Cart::add([
    458, // product id
    'Headphones', // product name
    199.99, // product price
    1, // quantity
    [], // attributes
    [
        [
            'name' => '10% Off', 
            'type' => 'discount', 
            'value' => '-10%'
        ]
    ] // conditions
]);

// add multiple items at one time
Cart::add(
    [
        456, # product id
        'Leather Shoes', # product name
        187, # product price
        1, # quantity
        [] # optional attributes
    ],
    [
        431, # product id
        'Leather Jacket', # product name
        254.50, # product price
        1, # quantity
        [] # optional attributes
    ]
);

Updating an item on a cart: Cart::update()

Cart::update(
    456, # product id
    [   
        'name' => 'New Item Name', // new item name
        'price' => 98.67, // new item price as a float or string
    ]
);

// updating a product's quantity
Cart::update(
    456, # product id
    [
    'quantity' => 2, // by default adding the quantity (so if from 4 to 6)
    ]
);

// reducing it...
Cart::update(
    456, 
    [
        'quantity' => -1, // so if from 4 to 3
    ]
);

// you can replace the quantity by setting relative to false
Cart::update(
    456, # product id
    [
        'quantity' => [
            'relative' => false,
            'value' => 5 // if the quantity was 2, it will now be 5
        ],
    ]
);

Removing an item on a cart: Cart::remove()

// Remove an item from the cart by its id
Cart::remove(456);

Getting an item on a cart: Cart::get()

// Get an item from the cart by its id
Cart::get(456);

// You can also get the total price of the item
$summedPrice = Cart::get($itemId)->getPriceSum();

Getting the cart content: Cart::getContent()

// Returns a collection of the cart's contents
$cartData = Cart::getContent();

// Gets the total number of items (not quantity) in the cart
$cartCollection->count();

// Transform the collection to an array or a JSON
$cartCollection->toArray();
$cartCollection->toJson();

Get cart total quantity: Cart::getTotalQuantity()

$cartTotalQuantity = Cart::getTotalQuantity();

Cart subtotal: Cart::getSubTotal()

$subTotal = Cart::getSubTotal();

Cart subtotal without conditions: Cart::getSubTotalWithoutConditions()

$subTotalWithoutConditions = Cart::getSubTotalWithoutConditions();

Cart Total: Cart::getTotal()

$total = Cart::getTotal();

Check if cart is empty: Cart::isEmpty()

Cart::isEmpty();

Clearing the Cart: Cart::clear()

This clears all items and conditions from the cart.

Cart::clear();

Clearing the cart items only: Cart::clearItems()

This clears all items, but keeps the conditions (useful for when you want to keep the conditions but remove the items)

Cart::clearItems();

Conditions

Conditions are very useful for adding things like discounts, taxes, shipping, etc.

Conditions can be added on the entire cart or on individual items, and can even be applied only at certain cart values.

Conditions on a cart level should always have a target of subtotal or total. This tells the cart which value to apply the condition to.

You can provide an optional minimum value which should be the dollar value in which the target (subtotal or total) needs to be for the condition to be active and impact the cart.

You can also provide an order to cart conditions which tells the cart in what order to apply the conditions. Item level conditions do not support the order parameter.

Conditions on the cart

Adding a condition to the cart: Cart::condition()
// Add a single condition to the cart
$condition = new \Joelwmale\Cart\CartCondition([
    'name' => 'Tax: 10%',
    'type' => 'tax',
    'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
    'value' => '10%',
    'attributes' => [ // add extra attributes here
    	'description' => 'Compulsory tax',
    ]
]);

Cart::condition($condition);

// Add multiple conditions
$tax = new \Joelwmale\Cart\CartCondition([
    'name' => 'Tax: 10%',
    'type' => 'tax',
    'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
    'value' => '10%',
    'order' => 2
]);

$shipping = new \Joelwmale\Cart\CartCondition([
    'name' => 'Shipping: $15',
    'type' => 'shipping',
    'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
    'value' => '+15',
    'order' => 1
]);

Cart::condition($tax);
Cart::condition($shipping);

// or as an array
Cart::condition([$tax, $shipping]);

// add condition to only apply on totals, not in subtotal
$shipping = new \Joelwmale\Cart\CartCondition([
    'name' => 'Express Shipping $15',
    'type' => 'shipping',
    'target' => 'total',
    'value' => '+15',
    'order' => 1
]);

Cart::condition($shipping);
Getting conditions on the cart: Cart::getConditions()
// To get all applied conditions on a cart, use below:
$cartConditions = Cart::getConditions();

foreach($cartConditions as $condition)
{
    $condition->getTarget(); // the target of which the condition was applied
    $condition->getName(); // the name of the condition
    $condition->getType(); // the type
    $condition->getValue(); // the value of the condition
    $condition->getOrder(); // the order of the condition
    $condition->getMinimum(); // the minimum dollar amount of the target, needed to activate the condition
    $condition->getMaximum(); // the maximum dollar amount of the target, needed to keep the condition active
    $condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added
}
Getting conditions on the cart as an array: Cart::getConditions(array: true)

You can get all cart conditions in array format by passing "array: true". This is useful if you want to store the carts conditions on a Livewire component since by default we have collections inside collections for conditions which Livewire does not support.

$cartConditions = Cart::getConditions(true);
$cartConditions = Cart::getConditions(active: true);

foreach ($cartConditions as $condition) {
    $condition['name']; // the name of the condition
    $condition['type']; // the type
    $condition['value']; // the value of the condition
    $condition['order']; // the order of the condition
    $condition['minimum']; // the minimum dollar amount of the target, needed to activate the condition
    $condition['maximum']; // the maximum dollar amount of the target, needed to keep the condition active
    $condition['attributes']; // the attributes of the condition, returns an empty [] if no attributes added
}
Getting conditions by name: Cart::getCondition($conditionName)
$condition = Cart::getCondition('GST');

$condition->getTarget(); // the target of which the condition was applied
$condition->getName(); // the name of the condition
$condition->getType(); // the type
$condition->getValue(); // the value of the condition
$condition->getMinimum(); // the minimum dollar amount of the target, needed to activate the condition
$condition->getMaximum(); // the maximum dollar amount of the target, needed to keep the condition active
$condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added
Getting active conditions on the cart: Cart::getConditions(active: true)

You can get only active conditions by passsing active: true to the getConditions() method.

This will return conditions that are actively being applied to the cart (i.e if they meet their minimum or maximum value)

$tenPercentOff = new CartCondition([
    'name' => '10% Off',
    'type' => 'discount',
    'target' => 'subtotal',
    'value' => '-10%',
    'minimum' => 120,
    'order' => 1,
]);

Cart::getConditions(active: true);

// will return "10% Off" if the subtotal of the cart is $200.
// will return no conditions if the subtotal is $100.

$shipping = new CartCondition([
    'name' => 'Shipping',
    'type' => 'discount',
    'target' => 'subtotal',
    'value' => '10',
    'maximum' => 200,
    'order' => 1,
]);

Cart::getConditions(active: true);

// will return "Shipping" if the subtotal of the cart is less than or equal 200
// will return no conditions if the subtotal is $210
Calculating condition value

There are 2 ways to calculate the value of a condition:

  1. Using the getCalculatedValue method on the condition instance
  2. Using the getCalculatedValueForCondition method on the cart instance and passing the condition name
Using the getCalculatedValue method on the condition instance
$subTotal = Cart::getSubTotal();
$condition = Cart::getCondition('10% GST');
$conditionCalculatedValue = $condition->getCalculatedValue($subTotal);
Using the getCalculatedValueForCondition method on the cart instance

This method automatically calculates the value of a condition by it's name based on the order of the conditions.

Cart::add([
    'id' => 1,
    'name' => 'Apple iPhone 15',
    'price' => 200,
    'quantity' => 1,
    'attributes' => [],
]);

$couponDiscount = new CartCondition([
    'name' => 'Coupon Discount',
    'type' => 'discount',
    'target' => 'subtotal',
    'value' => '-200',
    'order' => 1,
]);

$giftCard = new CartCondition([
    'name' => 'Gift Card',
    'type' => 'discount',
    'target' => 'subtotal',
    'value' => '-200',
    'order' => 2,
]);

Cart::getCalculatedValueForCondition('Coupon Discount'); // returns 200
Cart::getCalculatedValueForCondition('Gift Card'); // returns 0 as the coupon discount is applied first and brings the subtotal to 0
Adding conditions that activate once a minimum value is met

You can add a minimum amount required for a condition to activate.

This is useful for applying discounts only after certain cart values, i.e: 10% off for any purchases over $120.

$tenPercentOff = new CartCondition([
    'name' => '10% Off',
    'type' => 'discount',
    'target' => 'subtotal',
    'value' => '-10%',
    'minimum' => 120,
    'order' => 1,
]);

Cart::condition($tenPercentOff)
Adding conditions that only activate up to a maximum value

You can add a maximum amount required for a condition to activate.

This is useful for applying discounts up until amounts, i.e shipping for anything below $200, and free shipping above.

$shipping = new CartCondition([
    'name' => 'Shipping',
    'type' => 'discount',
    'target' => 'subtotal',
    'value' => '12',
    'maximum' => 200,
    'order' => 1,
]);

Cart::condition($shipping)

Conditions on items

Item conditions are useful if you have discounts to be applied specifically on an item and not on the whole cart value.

// lets create first our condition instance
$saleCondition = new \Joelwmale\Cart\CartCondition([
    'name' => '50% Off',
    'type' => 'tax',
    'value' => '-50%',
]);

// Create the product data with the condition
$product = [
    'id' => 456,
    'name' => 'Sample Item 1',
    'price' => 100,
    'quantity' => 1,
    'attributes' => [],
    'conditions' => $saleCondition
];

// Now add the product to the cart
Cart::add($product);

// You can of course also do multiple conditions on an item
$saleCondition = new \Joelwmale\Cart\CartCondition([
    'name' => 'SALE 5%',
    'type' => 'sale',
    'value' => '-5%',
]);

$discountCode = new CartCondition([
    'name' => 'Discount Code',
    'type' => 'promo',
    'value' => '-25',
]);

$item = [
    'id' => 456,
    'name' => 'Sample Item 1',
    'price' => 100,
    'quantity' => 1,
    'attributes' => [],
    'conditions' => [$saleCondition, $discountCode]
];

Cart::add($item);

NOTE: All cart per-item conditions should be added before calling Cart::getSubTotal()

Then Finally you can call Cart::getSubTotal() to get the Cart sub total with the applied conditions on each of the items.

// the subtotal will be calculated based on the conditions added that has target => "subtotal"
// and also conditions that are added on per item
$cartSubTotal = Cart::getSubTotal();
Add a condition to an existing item on the cart: Cart::addItemCondition($productId, $itemCondition)

Adding Condition to an existing Item on the cart is simple as well.

$condition = new CartCondition([
    'name' => 'COUPON 101',
    'type' => 'coupon',
    'value' => '-5%',
]);

Cart::addItemCondition(456, $condition);

Clearing Cart Conditions: Cart::clearCartConditions()

This clears all cart level conditions, and does not affect item level conditions.

Cart::clearCartConditions()

If you wish to clear all conditions from all items and the cart, use Cart::clearAllConditions()

Cart::clearAllConditions()
Remove a specific cart condtion: Cart::removeCartCondition($conditionName)
Cart::removeCartCondition('Summer Sale 5%')
Remove a specific item condition: Cart::removeItemCondition($itemId, $conditionName)
Cart::removeItemCondition(456, 'SALE 5%')
Clear all item conditions: Cart::clearItemConditions($itemId)
Cart::clearItemConditions(456)

Get conditions by type: Cart::getConditionsByType($type)

This returns all conditions that has been added to the cart by the type specified.

$tax = Cart::getConditionsByType('tax');
Remove conditions by type: Cart::removeConditionsByType($type)
Cart::removeConditionsByType('tax');

Cart Items

The method Cart::getContent() returns a collection of items.

Apart from the above methods, you can also get the price of an item with or without item level conditions applied.

These methods do not apply cart level conditions.

// With no conditions, just the price * quantity
$item->getPriceSum();

// With conditions applied get the price of a single quantity
$item->getPriceWithConditions();

// Get the sum with conditions applied
$item->getPriceSumWithConditions();

// Without conditions applied
$item->getPriceSumWithConditions();

Storage Options

By default the cart is stored in the session, but there are times you may want to store the cart in the database.

For instance, you may want to store the cart in the database so that the cart can be retrieved even after the user logs out or closes the browser, or you may want to add cart timeouts and support for multiple computers.

Session

The cart is stored in the session by default, using Laravel's in-built SessionManager.

Database Support

To get started, you'll need to create a new model for your Cart, the package requires only 3 columns, but you're free to extend this as you wish and add more columns.

You can utilise the events provided by the package to store additional information alongside the cart.

$table->string('session_id'); // this handles the session id of the cart
$table->text('items'); // this will store the cart items
$table->text('conditions'); // this will store the cart level conditions

Then add some json casts to your model and fillable columns:

protected $guarded = [];

protected $casts = [
    'items' => 'array',
    'conditions' => 'array',
];

Then update the configuration file to use the database driver:

'driver' => 'database',

'storage' => [
    'session',
    'database' => [
        'model' => \App\Models\Cart::class, // your model here
        'id' => 'session_id',
        'items' => 'items',
        'conditions' => 'conditions',
    ],
],

Events

The package provides a few events that you can listen to in order to manipulate the cart or take actions based on cart events.

LaravelCart.Created

This fires every time a cart is instantiated (i.e every time \Cart::add() is called)

Event::listen('LaravelCart.Added', function () {
    // cart was created
});

LaravelCart.Adding

This fires every time an item is being added to the cart

Event::listen('LaravelCart.Adding', function ($item) {
    // item is being added
});

LaravelCart.Added

This fires every time an item is successfully added to the cart

Event::listen('LaravelCart.Added', function ($item) {
    // item was added
});

LaravelCart.Updating

This fires every time an item is being updated

Event::listen('LaravelCart.Updating', function ($item) {
    // item is being updated
});

LaravelCart.Updated

This fires every time an item is successfully updated

Event::listen('LaravelCart.Updated', function ($item) {
    // item was updated
});

LaravelCart.Removing

This fires every time an item is being removed

Event::listen('LaravelCart.Removing', function ($item) {
    // item is being removed
});

LaravelCart.Removed

This fires every time an item is successfully removed

Event::listen('LaravelCart.Removed', function ($item) {
    // item was removed
});

LaravelCart.Clearing

This fires every time the cart is being cleared

Event::listen('LaravelCart.Clearing', function () {
    // cart is being cleared
});

LaravelCart.Cleared

This fires every time the cart is successfully cleared

Event::listen('LaravelCart.Cleared', function () {
    // cart was cleared
});

???? Credits

This package was orignally created by darryldecode but has since seen almost no updates. I have decided to take the old package and transform it into a new package with new features and updates.

???? License

The MIT License (MIT). Please see License File for more information.

joelwmale/laravel-cart 适用场景与选型建议

joelwmale/laravel-cart 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 23.15k 次下载、GitHub Stars 达 12, 最近一次更新时间为 2026 年 01 月 04 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「cart」 「laravel」 「shopping cart」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 joelwmale/laravel-cart 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 joelwmale/laravel-cart 我们能提供哪些服务?
定制开发 / 二次开发

基于 joelwmale/laravel-cart 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 23.15k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 12
  • 点击次数: 21
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 12
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-04