PHPackages                             isapp/laravel-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. [Framework](/categories/framework)
4. /
5. isapp/laravel-cart

ActiveLibrary[Framework](/categories/framework)

isapp/laravel-cart
==================

Is high customazible package for adding shopping cart functionality to Laravel applications

1.0.0(11mo ago)0156MITPHPPHP ^8.2

Since Jan 5Pushed 9mo agoCompare

[ Source](https://github.com/isap-ou/laravel-cart)[ Packagist](https://packagist.org/packages/isapp/laravel-cart)[ RSS](/packages/isapp-laravel-cart/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (2)Versions (3)Used By (0)

Laravel Cart
============

[](#laravel-cart)

**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.

[![Laravel cart](https://github.com/isap-ou/laravel-cart/raw/main/images/banner.jpg?raw=true)](https://github.com/isap-ou/laravel-cart)

[![Total Downloads](https://camo.githubusercontent.com/de10a63d3774c9a338f6de87d3dbe69ead7207adcc6158d90cef0214d9c5d884/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f69736170702f6c61726176656c2d636172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/isapp/laravel-cart)[![Latest Version on Packagist](https://camo.githubusercontent.com/c5f7510769ae5d18e64491746c0dede4a59995521c61a11bafed4ba29edebba0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f69736170702f6c61726176656c2d636172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/isapp/laravel-cart)

Features
--------

[](#features)

- ✅ Persistent cart storage (database/session)
- ✅ Guest and authenticated user support
- ✅ High precision price calculations
- ✅ Model associations
- ✅ Method chaining
- ✅ Exception handling

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

[](#installation)

To install the package, use Composer:

```
composer require isapp/laravel-cart
```

Publishing Configuration
------------------------

[](#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
---------------------------------

[](#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

[](#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
---------------

[](#getting-started)

### User Management

[](#user-management)

#### `getUser(): ?Authenticatable`

[](#getuser-authenticatable)

Returns the currently authenticated user or null if no user is set.

```
$user = Cart::getUser();
```

#### `setUser(Authenticatable $user): Driver`

[](#setuserauthenticatable-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`

[](#setguardstring-guard-driver)

Sets the authentication guard to use (default is 'web').

```
Cart::setGuard('admin')->getUser();
```

### Cart Management

[](#cart-management)

#### `get(): Model|Cart`

[](#get-modelcart)

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

[](#item-storage)

#### `storeItem(CartItemContract $item): Driver`

[](#storeitemcartitemcontract-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 CartItemProduct
- `ItemAssociatedWithDifferentCartException` - if trying to add item from another cart

#### `storeItems(Collection $items): static`

[](#storeitemscollection-items-static)

Stores multiple items in the cart at once.

```
$items = collect([
    $cartItem1,
    $cartItem2,
    $cartItem3
]);
Cart::storeItems($items);
```

### Quantity Management

[](#quantity-management)

#### `increaseQuantity(CartItemContract $item, int $quantity = 1): static`

[](#increasequantitycartitemcontract-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`

[](#decreasequantitycartitemcontract-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

[](#item-removal)

#### `removeItem(CartItemContract $item): Driver`

[](#removeitemcartitemcontract-item-driver)

Removes a specific item from the cart completely.

```
Cart::removeItem($cartItem);
```

#### `emptyCart(): static`

[](#emptycart-static)

Removes all items from the cart.

```
Cart::emptyCart();
```

### Price Calculations

[](#price-calculations)

#### `getItemPrice(CartItemContract $item, bool $incTaxes = true): string`

[](#getitempricecartitemcontract-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`

[](#getitempriceperunitcartitemcontract-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`

[](#gettotalpricebool-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

[](#usage-examples)

#### Basic Cart Operations

[](#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

[](#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

[](#quantity-management-1)

```
// 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

[](#price-calculations-1)

```
$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

[](#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

[](#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 `CartItemProduct` interface
- The driver uses eager loading to optimize database queries

Adding a Custom Driver to Laravel Facade via Extend
---------------------------------------------------

[](#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:

1. 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...
    }
    ```
2. 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
---------

[](#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
------------

[](#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
-------

[](#license)

This project is open-sourced software licensed under the [MIT License](https://opensource.org/licenses/MIT).

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](https://isapp.be) and [ISAP OÜ](https://isap.me).
Check out our software development services at [isapp.be](https://isapp.be).

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance54

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

336d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9bfb1eae1e3e43813da6740e5eaa39307a95db7561c2d27e7e8aa24233cdcbeb?d=identicon)[andrii-trush](/maintainers/andrii-trush)

---

Top Contributors

[![andrii-trush](https://avatars.githubusercontent.com/u/14265776?v=4)](https://github.com/andrii-trush "andrii-trush (13 commits)")

---

Tags

cartecommercelaravellibraryredisphpframeworklaravellaravel-packagecarte-commerce

###  Code Quality

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/isapp-laravel-cart/health.svg)

```
[![Health](https://phpackages.com/badges/isapp-laravel-cart/health.svg)](https://phpackages.com/packages/isapp-laravel-cart)
```

###  Alternatives

[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M201](/packages/laravel-ai)[binafy/laravel-stub

Generate stub files easy

100180.5k19](/packages/binafy-laravel-stub)[richarddobron/laravel-fbt

A PHP Internationalization Framework for Laravel Application.

128.3k](/packages/richarddobron-laravel-fbt)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
