PHPackages                             treestoneit/shopping-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. treestoneit/shopping-cart

ActiveLibrary[Framework](/categories/framework)

treestoneit/shopping-cart
=========================

An easy-to-use shopping cart for Laravel

v1.6.1(3mo ago)6263.0k↑784.9%9[3 issues](https://github.com/treeStoneIT/shopping-cart/issues)2MITPHPPHP ^8.2|^8.3|^8.4

Since Oct 7Pushed 3mo ago7 watchersCompare

[ Source](https://github.com/treeStoneIT/shopping-cart)[ Packagist](https://packagist.org/packages/treestoneit/shopping-cart)[ Docs](https://github.com/treestoneit/shopping-cart)[ GitHub Sponsors](https://github.com/treestoneit)[ RSS](/packages/treestoneit-shopping-cart/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (19)Used By (2)

A Database Driven Shopping Cart for Laravel
===========================================

[](#a-database-driven-shopping-cart-for-laravel)

[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Latest Version on Packagist](https://camo.githubusercontent.com/34f88f7b8ca344de81319cc048a921ff72345451f22c5516ffecd962ae9d6453/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7472656573746f6e6569742f73686f7070696e672d636172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/treestoneit/shopping-cart)[![Total Downloads](https://camo.githubusercontent.com/795e98417f34045e3449ffc6a00b8630390e1de98a47378627a7761b2e84d30e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7472656573746f6e6569742f73686f7070696e672d636172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/treestoneit/shopping-cart)[![Build Status](https://camo.githubusercontent.com/82e44bbb015f7b392ffe9f80e4919508a53381f05170aa0c221cb2c308842521/68747470733a2f2f7472617669732d63692e636f6d2f7472656553746f6e6549542f73686f7070696e672d636172742e7376673f6272616e63683d6d6173746572)](https://travis-ci.com/treeStoneIT/shopping-cart)[![StyleCI](https://camo.githubusercontent.com/162e3c672290d086116041e345779d18bd3cd91e820c11c027c46a1e3b68ef68/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3231333237303034392f736869656c643f6272616e63683d6d6173746572)](https://github.styleci.io/repos/213270049)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/a31485c9e411de7ee0c361cb9444992bd814fc23a2391cf570e2fb925b680952/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7472656553746f6e6549542f73686f7070696e672d636172742f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/treeStoneIT/shopping-cart/?branch=master)

This is a simple shopping cart implementation for Laravel 6/7/8. It automatically serializes your cart to the database and loads the related product models.

Usage
-----

[](#usage)

To get started, add the `Buyable` interface to your model.

```
use Illuminate\Database\Eloquent\Model;
use Treestoneit\ShoppingCart\Buyable;
use Treestoneit\ShoppingCart\BuyableTrait;

class Product extends Model implements Buyable
{
    use BuyableTrait;
}
```

Make sure you implement the `getBuyableDescription` and `getBuyablePrice` methods with the respective product description and product price.

Now you can add products to the cart.

```
use Treestoneit\ShoppingCart\Facades\Cart;

$product = Product::create(['name' => 'Pizza Slice', 'price' => 1.99]);
$quantity = 2;

Cart::add($product, $quantity);
```

To retrieve the cart contents:

```
Cart::content();
// or
Cart::items();
```

To retrieve the total:

```
Cart::subtotal();
```

You can update the quantity of an item in the cart. The first argument is the primary id of the related `CartItem`.

```
$item = Cart:content()->first();

Cart::update($item->id, $item->quantity + 5);
```

Or remove the item completely.

```
Cart::remove($item->id);
```

### Options

[](#options)

To add item-specific options (such as size or color) to an item in the cart, first register available options in your `Buyable` instance.

```
class Product extends Model implements Buyable
{
    // ...

    public function getOptions(): array
    {
        return [
            'size' => ['18 inch', '36 inch'],
            'color' => ['white', 'blue', 'black'],
        ];
    }
}
```

Then you just pass an associative array as the third parameter of `Cart::add`.

```
Cart::add($product, 3, ['color' => 'white']);
```

Any invalid options will be silently removed from the array.

You can also add or change options of an item currently in the cart by calling `Cart::updateOption`.

```
$item = Cart:content()->first();

// Update a single option
Cart::updateOption($item->id, 'color', 'black');

// Update multiple options at once
Cart::updateOptions($item->id, [
    'color' => 'black',
    'size' => '36 inch',
]);
```

The options array will be available on the `CartItem` instance as `$item->options`.

### Attaching to Users

[](#attaching-to-users)

You can attach a cart instance to a user, so that their cart from a previous session can be retrieved. Attaching a cart to a user is acheived by calling the `attachTo` method, passing in an instance of `Illuminate\Contracts\Auth\Authenticatable`.

```
class RegisterController
{
    /**
     * The user has been registered.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function registered(Request $request, $user)
    {
        Cart::attachTo($user);
    }
}
```

Then when the user logs in, you can call the `loadUserCart` method, again passing the user instance.

```
class LoginController
{
    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        Cart::loadUserCart($user);
    }
}
```

### Dependency Injection

[](#dependency-injection)

If you're not a facade person, you can use the container to inject the shopping cart instance by type-hinting the `Treestoneit\ShoppingCart\CartManager` class, or the `Treestoneit\ShoppingCart\CartContract` interface.

### Tax

[](#tax)

The shopping cart can calculate the total tax of the items in the cart. Just call

```
$rate = 13; // The tax rate as a percentage

Cart::tax($rate);
```

You can also set a default tax rate in the included config file.

```
// config/shopping-cart.php

    'tax' => [
        'rate' => 6,
    ],
```

Then just call `Cart::tax` without a parameter.

```
Cart::tax();
```

If some of your items have different tax rates applicable to them, or are tax-free, no problem. First modify the config file:

```
// config/shopping-cart.php

    'tax' => [
        'mode' => 'per-item',
    ],
```

Then, set the tax rate per item by implementing the `Taxable` interface and defining a `getTaxRate` method.

```
use Treestoneit\ShoppingCart\Taxable;

class Product extends Model implements Buyable, Taxable
{
    /**
     * Calculate the tax here based on a database column, or whatever you will.
     *
     * @return int|float
     */
    public function getTaxRate()
    {
        if ($this->tax_rate) {
            return $this->tax_rate;
        }

        if (! $this->taxable) {
            return 0;
        }

        return 8;
    }
```

Now your items will have their custom tax rate applied to them when calling `Cart::tax`.

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

[](#installation)

You can install the package via composer:

```
composer require treestoneit/shopping-cart
```

To publish the config file and migrations, run

```
php artisan vendor:publish --provider="Treestoneit\ShoppingCart\CartServiceProvider"
```

And run the included database migrations.

```
php artisan migrate
```

Testing
-------

[](#testing)

```
composer test
```

Starter (demo) Repository
-------------------------

[](#starter-demo-repository)

If you would like to see a starter/demo implementation using this shopping cart please check out our [laravel-commerce repository](https://github.com/treeStoneIT/laravel-commerce)

Roadmap
-------

[](#roadmap)

Some things I didn't get around to yet:

- Clear cart instance which has not been attached to a user when session is destroyed.
- Add an Artisan command that will clear any unattached carts (these two might be mutually exclusive)
- Add ability to configure cart merging strategy when `loadUserCart` is called

Credits
-------

[](#credits)

- Created by [Avraham Appel](https://github.com/treestoneit)
- Initial development sponsored by [Bomshteyn Consulting](https://bomshteyn.com)
- Inspired by [LaravelShoppingcart package](https://github.com/Crinsane/LaravelShoppingcart) by [@Crisane](https://github.com/Crinsane)

License
-------

[](#license)

The MIT License (MIT). Please see the [License File](LICENSE.md) for more information.

Laravel Package Boilerplate
---------------------------

[](#laravel-package-boilerplate)

This package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com).

###  Health Score

62

—

FairBetter than 99% of packages

Maintenance85

Actively maintained with recent releases

Popularity42

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity83

Battle-tested with a long release history

 Bus Factor2

2 contributors hold 50%+ of commits

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

Every ~135 days

Recently: every ~455 days

Total

18

Last Release

102d ago

PHP version history (6 changes)v1.0.0PHP ^7.1

v1.3.0PHP ^7.2

v1.4.0PHP ^7.3

v1.4.1PHP ^7.3|^8.0

v1.5.0PHP ^7.3|^8.0|^8.1

v1.6.0PHP ^8.2|^8.3|^8.4

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/44207441?v=4)[Bomshteyn Consulting](/maintainers/treeStoneIT)[@treeStoneIT](https://github.com/treeStoneIT)

![](https://www.gravatar.com/avatar/c5380728b99919e632776bbe389056c34beb2ae339e4f8f2a66285345549b48f?d=identicon)[avrahamappel](/maintainers/avrahamappel)

---

Top Contributors

[![bomshteyn](https://avatars.githubusercontent.com/u/4259699?v=4)](https://github.com/bomshteyn "bomshteyn (29 commits)")[![avrahamappel](https://avatars.githubusercontent.com/u/33736292?v=4)](https://github.com/avrahamappel "avrahamappel (26 commits)")[![shcherse](https://avatars.githubusercontent.com/u/15324892?v=4)](https://github.com/shcherse "shcherse (3 commits)")[![tominon](https://avatars.githubusercontent.com/u/508519?v=4)](https://github.com/tominon "tominon (2 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (1 commits)")

---

Tags

e-commerceecommerce-frameworklaravellaravel-packageshopping-cartlaravelshopping carttreestoneit

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/treestoneit-shopping-cart/health.svg)

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

###  Alternatives

[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M529](/packages/laravel-passport)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k25.9M106](/packages/laravel-cashier)[laravel/scout

Laravel Scout provides a driver based solution to searching your Eloquent models.

1.7k49.4M479](/packages/laravel-scout)[laravel/pennant

A simple, lightweight library for managing feature flags.

57311.1M53](/packages/laravel-pennant)[cmgmyr/messenger

Simple user messaging tool for Laravel

2.6k2.4M6](/packages/cmgmyr-messenger)

PHPackages © 2026

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