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

ActiveLibrary[Framework](/categories/framework)

tefo/cart
=========

shopping cart for laravel

3.0.2(5y ago)28MITPHP

Since Mar 14Pushed 5y agoCompare

[ Source](https://github.com/Tefoh/Cart)[ Packagist](https://packagist.org/packages/tefo/cart)[ RSS](/packages/tefo-cart/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (8)Versions (25)Used By (0)

Laravel cart
------------

[](#laravel-cart)

[![Build Status](https://camo.githubusercontent.com/e2b980839f9a43719e1bb34fa9155678cf56beb3dee9f3359f7690f4b8ea539a/68747470733a2f2f7472617669732d63692e6f72672f5465666f682f436172742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/Tefoh/Cart)[![Total Downloads](https://camo.githubusercontent.com/b1d360e1c8026b9adc53dc608b88d3b397b30ce9753ef60952f485835cda1122/68747470733a2f2f706f7365722e707567782e6f72672f7465666f2f636172742f646f776e6c6f6164732e706e67)](https://packagist.org/packages/tefo/cart)[![Latest Stable Version](https://camo.githubusercontent.com/43e069071d60d21abfc3cd8c6947c72385abc4e9b9d694a2e6b78d74bcb861ea/68747470733a2f2f706f7365722e707567782e6f72672f7465666f2f636172742f762f737461626c65)](https://packagist.org/packages/tefo/cart)[![License](https://camo.githubusercontent.com/c0109dfe18264c48f6f0605fe6978dfc26b14e8ed4b2cc68c0ecce7c5fafd145/68747470733a2f2f706f7365722e707567782e6f72672f7465666f2f636172742f6c6963656e7365)](https://packagist.org/packages/tefo/cart)

A simple shopping cart implementation for Laravel.

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

[](#installation)

Install the package through [Composer](http://getcomposer.org/).

Run the Composer require command from the Terminal:

```
composer require tefo/cart

```

Now you're ready to start using the cart in your application.

Overview
--------

[](#overview)

Look at one of the following topics to learn more about cart

- [Usage](#usage)
- [Collections](#collections)
- [Instances](#instances)
- [Models](#models)
- [Exceptions](#exceptions)
- [Events](#events)
- [Example](#example)

Usage
-----

[](#usage)

first implement your models want to add to your cart `HasCart` interface:

```
use Tefo\Cart\HasCart;
use Tefo\Cart\InteractsWithCard;

class Product extends Model implements HasCart
{
    use InteractsWithCard;
    // ...
}
```

Now you can use the following methods of cart to use:

### Cart::addItem()

[](#cartadditem)

For add one item to cart use this method. for first parameter it excepts a product that implements `HasCart` or an array.

```
Cart::addItem($product);
```

this method has optional parameters, for second parameter you can set products options like quantity. if quantity not set by default it will be 1. for third optional option you can set product variation like `['color' => 'red']`.

```
Cart::addItem($product, ['quantity' => 2], ['color' => 'red']);
```

### Cart::add()

[](#cartadd)

Adding multiple items to the cart is really simple, you just use the `add()` method, which accepts a variety of parameters.

for first parameter excepts an array of products info, every product can be an eloquent model or an array.

```
Cart::add([$product_1, $product_2]);
```

for second array it excepts an array options for each product like product quantity but its optional. last parameter that its optional too it excepts an array each product variations.

```
Cart::add([$product_1, $product_2], [['quantity' => 1], ['quantity' => 2]], [$product_1_Variation, $product_2_Variation]);
```

**The `add()` method will return a collection CartItem instance of the item you just added to the cart.**

### Cart::update()

[](#cartupdate)

To update an item in the cart, you'll first need the itemId of the item. Next you can use the `update()` method to update it.

If you want to update more attributes of the item, you can either pass the update method an array or a `HasCart` as the second parameter. This way you can update all information of the item with the given itemId.

```
$itemId = '92e1b081-17b9-4f7a-8f91-91da9dbcd6ca'; // its uuid

Cart::update($itemId, $updatedProduct); // Will update the id, name and price

Cart::update($itemId, ['name' => 'Product 1']); // Will update the name
```

If you simply want to update the quantity, you'll pass the update method the itemId and the new quantity:

```
$itemId = '92e1b081-17b9-4f7a-8f91-91da9dbcd6ca';

Cart::updateQuantity($itemId, 2); // Will update the quantity
```

### Cart::remove()

[](#cartremove)

To remove an item for the cart, you'll again need the itemId. This itemId you simply pass to the `remove()` method and it will remove the item from the cart.

```
$itemId = '92e1b081-17b9-4f7a-8f91-91da9dbcd6ca';

Cart::remove($itemId);
```

### Cart::get()

[](#cartget)

If you want to get an item from the cart using its itemId, you can simply call the `get()` method on the cart and pass it the itemId.

```
$itemId = '92e1b081-17b9-4f7a-8f91-91da9dbcd6ca';

Cart::get($itemId);
```

### Cart::content()

[](#cartcontent)

Of course you also want to get the carts content. This is where you'll use the `content` method. This method will return a Collection of CartItems which you can iterate over and show the content to your customers.

```
Cart::content();
```

This method will return the content of the current cart instance, if you want the content of another instance, simply chain the calls.

```
Cart::session('wishlist')->content();
```

### Cart::destroy()

[](#cartdestroy)

If you want to completely remove the content of a cart, you can call the destroy method on the cart. This will remove all CartItems from the cart for the current cart instance.

```
Cart::destroy();
```

### Cart::total()

[](#carttotal)

The `total()` method can be used to get the calculated total of all items in the cart, given there price and quantity.

```
Cart::total();
```

The method will automatically format the result, which you can tweak using the three optional parameters

```
Cart::total($decimals, $decimalSeperator, $thousandSeperator);
```

You can set the default number format in the config file.

**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the total property `$cart->total`**

### Cart::tax()

[](#carttax)

The `tax()` method can be used to get the calculated amount of tax for all items in the cart, given there price and quantity.

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

The method will automatically format the result, which you can tweak using the three optional parameters

```
Cart::tax($decimals, $decimalSeperator, $thousandSeperator);
```

You can set the default number format in the config file.

**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the tax property `$cart->tax`**

### Cart::subtotal()

[](#cartsubtotal)

The `subtotal()` method can be used to get the total of all items in the cart, minus the total amount of tax.

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

The method will automatically format the result, which you can tweak using the three optional parameters

```
Cart::subtotal($decimals, $decimalSeperator, $thousandSeperator);
```

You can set the default number format in the config file.

**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->subtotal`**

### Cart::count()

[](#cartcount)

If you want to know how many items there are in your cart, you can use the `count()` method. This method will return the total number of items in the cart. So if you've added 2 books and 1 shirt, it will return 3 items.

```
Cart::count();
```

### Cart::search()

[](#cartsearch)

To find an item in the cart, you can use the `search()` method.

Behind the scenes, the method simply uses the filter method of the Laravel Collection class. This means you must pass it a Closure in which you'll specify you search terms.

If you for instance want to find all items with an id of 1:

```
$cart->search(function ($cartItem, $itemId) {
	return $cartItem->id === 1;
});
```

As you can see the Closure will receive two parameters. The first is the CartItem to perform the check against. The second parameter is the itemId of this CartItem.

**The method will return a Collection containing all CartItems that where found**

This way of searching gives you total control over the search process and gives you the ability to create very precise and specific searches.

Collections
-----------

[](#collections)

On multiple instances the Cart will return to you a Collection. This is just a simple Laravel Collection, so all methods you can call on a Laravel Collection are also available on the result.

As an example, you can quickly get the number of unique products in a cart:

```
Cart::content()->count();
```

Or you can group the content by the id of the products:

```
Cart::content()->groupBy('id');
```

Instances
---------

[](#instances)

The packages supports multiple instances of the cart. The way this works is like this:

You can set the current instance of the cart by calling `Cart::session('newInstance')`. From this moment, the active instance of the cart will be `newInstance`, so when you add, remove or get the content of the cart, you're work with the `newInstance` instance of the cart. If you want to switch instances, you just call `Cart::session('otherInstance')` again, and you're working with the `otherInstance` again.

So a little example:

```
Cart::session('shopping')->addItem(['id' => 1, 'name' => 'Product 1', 'price' => 9.99], ['quantity' => 1]);

// Get the content of the 'shopping' cart
Cart::content();

Cart::session('wishlist')->addItem($product_2, ['quantity' => 2], ['size' => 'medium']);

// Get the content of the 'wishlist' cart
Cart::content();

// If you want to get the content of the 'shopping' cart again
Cart::session('shopping')->content();

// And the count of the 'wishlist' cart again
Cart::session('wishlist')->count();
```

**N.B. Keep in mind that the cart stays in the last set instance for as long as you don't set a different one during script execution.**

**N.B.2 The default cart instance is called `default`, so when you're not using instances,`Cart::content();` is the same as `Cart::instance('default')->content()`.**

Models
------

[](#models)

Because it can be very convenient to be able to directly access a model from a CartItem is it possible to associate a model with the items in the cart. Let's say you have a `Product` model in your application. With the `associate()` method, you can tell the cart that an item in the cart, is associated to the `Product` model.

That way you can access your model right from the `CartItem`!

The model can be accessed via the `model` property on the CartItem.

**If your model implements the `HasCart` interface and you used your model to add the item to the cart, it will associate automatically.**

Here is an example:

```
// First we'll add the item to the cart.
$cartItem = Cart::addItem(['id' => 1, 'name' => 'Product 1', 'price' => 9.99], ['quantity' => 2], ['size' => 'large']);

// Next we associate a model with the item.
Cart::associate($cartItem->itemId, 'Product');

// Or even easier, call the associate method on the CartItem!
$cartItem->associate('Product');

// You can even make it a one-liner
Cart::addItem(['id' => 2, 'name' => 'Product 2', 'price' => 9.99], ['quantity' => 1], ['size' => 'large'])->associate('Product');

// Now, when iterating over the content of the cart, you can access the model.
foreach(Cart::content() as $row) {
	echo 'You have ' . $row->quantity . ' items of ' . $row->model->name . ' with description: "' . $row->model->description . '" in your cart.';
}
```

### Configuration

[](#configuration)

To publish the `config` file.

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

```

This will give you a `cart.php` config file in which you can make the changes.

Exceptions
----------

[](#exceptions)

The Cart package will throw exceptions if something goes wrong. This way it's easier to debug your code using the Cart package or to handle the error based on the type of exceptions. The Cart packages can throw the following exceptions:

ExceptionReason*InvalidRowIDException*When the itemId that got passed doesn't exists in the current cart instance*UnknownModelException*When you try to associate an none existing model to a CartItem.Events
------

[](#events)

The cart also has events build in. There are five events available for you to listen for.

EventFiredParametercart.item.addedWhen an item was added to the cart.The `CartItem` that was added.cart.item.updatedWhen an item in the cart was updated.The `CartItem` that was updated.cart.item.removedWhen an item is removed from the cart.The `CartItem` that was removed.Example
-------

[](#example)

Below is a little example of how to list the cart content in a table:

```
// Add some items in your Controller.
Cart::addItem(['id' => 1, 'name' => 'Product 1', 'price' => 9.99], ['quantity' => 1]);
Cart::addItem(['id' => 2, 'name' => 'Product 2', 'price' => 5.95], ['quantity' => 2], ['size' => 'large']);

// Display the content in a View.

           	Product
           	Quantity
           	Price
           	Subtotal

   		@foreach(Cart::content() as $row)

               		{{ $row->name }}
               		@if($row->variation->has('size')) {{ $row->variation->size }} @endif

           		${{ $row->price }}
           		${{ $row->total }}

	   	@endforeach

   			&nbsp;
   			Subtotal
   			{{ Cart::subtotal() }}

   			&nbsp;
   			Tax
   			{{ Cart::tax() }}

   			&nbsp;
   			Total
   			{{ Cart::total() }}

```

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity73

Established project with proven stability

 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

Every ~116 days

Recently: every ~278 days

Total

23

Last Release

1898d ago

Major Versions

1.3 → 2.0.02016-06-15

2.6.0 → 3.02021-03-06

PHP version history (2 changes)1.0PHP &gt;=5.3.0

1.3PHP &gt;=5.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/31caa706fbe13f6fbb24e5681a46fe2ccfb64d4511ae8fae43ef052bf933328b?d=identicon)[tefo\_h](/maintainers/tefo_h)

---

Top Contributors

[![Tefoh](https://avatars.githubusercontent.com/u/26341440?v=4)](https://github.com/Tefoh "Tefoh (2 commits)")

---

Tags

laravelcartshoppingcart

###  Code Quality

TestsPHPUnit

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/tefo-cart/health.svg)](https://phpackages.com/packages/tefo-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.0M532](/packages/laravel-passport)[lukepolo/laracart

A simple cart for Laravel

583135.4k1](/packages/lukepolo-laracart)[laravel-zero/framework

The Laravel Zero Framework.

3371.4M369](/packages/laravel-zero-framework)[anayarojo/shoppingcart

Laravel Shoppingcart

57175.5k](/packages/anayarojo-shoppingcart)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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