isapp/laravel-cart
Composer 安装命令:
composer require isapp/laravel-cart
包简介
Is high customazible package for adding shopping cart functionality to Laravel applications
README 文档
README
Laravel Cart is a highly customizable package that enables you to easily add shopping cart functionality to your Laravel applications. With flexible options for item management, persistent storage, and deep integration with Laravel, it is perfect for building e-commerce or custom shopping features.
Features
- ✅ Persistent cart storage (database/session)
- ✅ Guest and authenticated user support
- ✅ High precision price calculations
- ✅ Model associations
- ✅ Method chaining
- ✅ Exception handling
Installation
To install the package, use Composer:
composer require isapp/laravel-cart
Publishing Configuration
To modify the default configuration, publish the configuration file using the following Artisan command:
php artisan vendor:publish --provider="Isapp\LaravelCart\CartServiceProvider" --tag="config"
This command will create a config/laravel-cart.php file where you can customize package settings as needed.
Publishing and Running Migrations
To publish the migration files provided by the Laravel Cart package, use the following Artisan command:
php artisan vendor:publish --provider="Isapp\LaravelCart\CartServiceProvider" --tag="migrations"
This command will copy the migration files to your project's database/migrations directory.
Running the Migrations
Once the migration files are published, you can apply the migrations to your database using the following command:
php artisan migrate
Getting Started
User Management
getUser(): ?Authenticatable
Returns the currently authenticated user or null if no user is set.
$user = Cart::getUser();
setUser(Authenticatable $user): Driver
Sets a specific user for cart operations. Useful for admin operations or impersonation.
$user = User::find(1); Cart::setUser($user)->storeItem($item);
setGuard(string $guard): Driver
Sets the authentication guard to use (default is 'web').
Cart::setGuard('admin')->getUser();
Cart Management
get(): Model|Cart
Gets or creates the cart for the current user or session. For authenticated users, finds or creates cart by user_id. For guests, uses session_id.
$cart = Cart::get(); echo "Cart has " . $cart->items->count() . " items";
Item Storage
storeItem(CartItemContract $item): Driver
Stores a single item in the cart. If the item already exists, increases its quantity instead.
$product = Product::find(1); $cartItem = new CartItem(); $cartItem->itemable()->associate($product); Cart::storeItem($cartItem);
Throws:
NotImplementedException- if itemable doesn't implement CartItemProductItemAssociatedWithDifferentCartException- if trying to add item from another cart
storeItems(Collection $items): static
Stores multiple items in the cart at once.
$items = collect([ $cartItem1, $cartItem2, $cartItem3 ]); Cart::storeItems($items);
Quantity Management
increaseQuantity(CartItemContract $item, int $quantity = 1): static
Increases the quantity of a specific cart item.
// Increase by 1 (default) Cart::increaseQuantity($cartItem); // Increase by specific amount Cart::increaseQuantity($cartItem, 5);
Throws:
NotFoundException- if item doesn't exist in cart
decreaseQuantity(CartItemContract $item, int $quantity = 1): Driver
Decreases the quantity of a specific cart item.
// Decrease by 1 (default) Cart::decreaseQuantity($cartItem); // Decrease by specific amount Cart::decreaseQuantity($cartItem, 3);
Throws:
NotFoundException- if item doesn't exist in cart
Item Removal
removeItem(CartItemContract $item): Driver
Removes a specific item from the cart completely.
Cart::removeItem($cartItem);
emptyCart(): static
Removes all items from the cart.
Cart::emptyCart();
Price Calculations
getItemPrice(CartItemContract $item, bool $incTaxes = true): string
Calculates the total price for a cart item (price × quantity). Returns a string for precision.
// With taxes (default) $totalPrice = Cart::getItemPrice($cartItem); // Without taxes $totalPrice = Cart::getItemPrice($cartItem, false);
getItemPricePerUnit(CartItemContract $item, bool $incTaxes = true): string
Gets the price per single unit of a cart item.
// With taxes (default) $unitPrice = Cart::getItemPricePerUnit($cartItem); // Without taxes $unitPrice = Cart::getItemPricePerUnit($cartItem, false);
getTotalPrice(bool $incTaxes = true): string
Calculates the total price of all items in the cart.
// With taxes (default) $total = Cart::getTotalPrice(); // Without taxes $total = Cart::getTotalPrice(false);
Usage Examples
Basic Cart Operations
use Isapp\LaravelCart\Facades\Cart; use App\Models\Product; use Isapp\LaravelCart\Models\CartItem; // Create and add item to cart $product = Product::find(1); $cartItem = new CartItem(); $cartItem->itemable()->associate($product); Cart::storeItem($cartItem); // Get cart with items $cart = Cart::get(); echo "Items in cart: " . $cart->items->count(); // Calculate totals $total = Cart::getTotalPrice(); echo "Cart total: $" . $total;
Working with Different Users
// Admin adding items to user's cart $user = User::find(123); $product = Product::find(1); $cartItem = new CartItem(); $cartItem->itemable()->associate($product); Cart::setUser($user)->storeItem($cartItem);
Quantity Management
// Get existing cart item $cart = Cart::get(); $cartItem = $cart->items->first(); // Increase quantity Cart::increaseQuantity($cartItem, 2); // Decrease quantity Cart::decreaseQuantity($cartItem, 1); // Remove item completely Cart::removeItem($cartItem);
Price Calculations
$cart = Cart::get(); foreach ($cart->items as $item) { $unitPrice = Cart::getItemPricePerUnit($item); $totalItemPrice = Cart::getItemPrice($item); echo "Unit: $unitPrice, Total: $totalItemPrice\n"; } $grandTotal = Cart::getTotalPrice(); echo "Grand Total: $grandTotal";
Error Handling
The DatabaseDriver throws specific exceptions for different error conditions:
use Isapp\LaravelCart\Exceptions\NotFoundException; use Isapp\LaravelCart\Exceptions\NotImplementedException; use Isapp\LaravelCart\Exceptions\ItemAssociatedWithDifferentCartException; try { Cart::increaseQuantity($cartItem, 5); } catch (NotFoundException $e) { // Item not found in cart return response()->json(['error' => 'Item not found'], 404); } catch (NotImplementedException $e) { // Itemable doesn't implement required interface return response()->json(['error' => 'Invalid item'], 400); } catch (ItemAssociatedWithDifferentCartException $e) { // Trying to add item from another cart return response()->json(['error' => 'Item belongs to different cart'], 400); }
Notes
- All price calculations use BCMath for high precision arithmetic
- Prices are returned as strings to maintain precision
- The driver supports both authenticated users and guest sessions
- Method chaining is supported for fluent interface
- Cart items must implement
CartItemProductinterface - The driver uses eager loading to optimize database queries
Adding a Custom Driver to Laravel Facade via Extend
If you need to add a custom driver to the Cart facade, you can do so by extending it within a service provider.
Here is an example demonstrating how to achieve this:
-
Create a custom driver class, for example:
namespace App\Services; use Isapp\LaravelCart\Contracts\Driver; class CustomCartDriver implements Driver { // Implement methods as per the contract and your needs public function storeItem(CartItemContract $item): Driver { // Custom implementation } public function increaseQuantity(CartItemContract $item, int $quantity = 1): static { // Custom implementation } // Other required methods... }
-
Register the custom driver in a service provider:
namespace App\Providers; use Illuminate\Support\ServiceProvider; use Isapp\LaravelCart\Facades\Cart; class CartServiceProvider extends ServiceProvider { public function boot() { Cart::extend('custom', function () { return new \App\Services\CustomCartDriver; }); } }
ToDo List
- Add automated cleanup for expired cart sessions
- Add method to get total items count in cart
- Add method to get total quantity of all items
- Add method to find item by ID
- Add method to check if specific item exists in cart
- Add stock validation before adding items
- Add events firing (ItemAdded, ItemRemoved, etc.)
- Add method to merge carts (guest → user)
Contributing
Contributions are welcome! If you have suggestions for improvements, new features, or find any issues, feel free to submit a pull request or open an issue in this repository.
Thank you for helping make this package better for the community!
License
This project is open-sourced software licensed under the MIT License.
You are free to use, modify, and distribute it in your projects, as long as you comply with the terms of the license.
Maintained by ISAPP and ISAP OÜ.
Check out our software development services at isapp.be.
isapp/laravel-cart 适用场景与选型建议
isapp/laravel-cart 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 156 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 07 月 31 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「framework」 「php」 「cart」 「laravel」 「e-commerce」 「laravel-package」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 isapp/laravel-cart 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 isapp/laravel-cart 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 isapp/laravel-cart 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
PHP Framework HLEB2 is the foundation of the web application. Provides ease of development and application performance.
Laravel 11 and above Shopping cart
Admin Hub for GetCandy. A modern headless e-commerce solution for Laravel PHP framework.
universal shopping basket
A PHP (and Laravel) package to interface with the Snipcart api.
Package set to provide shop or e-commerce functionality (such as CART, ORDERS, TRANSACTIONS and ITEMS) to Laravel for customizable builds.
统计信息
- 总下载量: 156
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 15
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-31
