PHPackages                             centrex/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. [Database &amp; ORM](/categories/database)
4. /
5. centrex/laravel-cart

ActiveLibrary[Database &amp; ORM](/categories/database)

centrex/laravel-cart
====================

Shopping cart for Laravel with session, cookie, and database storage, Livewire components, and REST API

v0.2.2(1mo ago)037MITPHPPHP ^8.3CI passing

Since Apr 11Pushed 1mo agoCompare

[ Source](https://github.com/centrex/laravel-cart)[ Packagist](https://packagist.org/packages/centrex/laravel-cart)[ Docs](https://github.com/centrex/laravel-cart)[ RSS](/packages/centrex-laravel-cart/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (16)Versions (6)Used By (0)

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

[](#laravel-cart)

[![Latest Version on Packagist](https://camo.githubusercontent.com/9073eaf8ac2a300240281b734a612f5fdc38ff3987ea1b51e0dd3e62a9fe8c43/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f63656e747265782f6c61726176656c2d636172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/centrex/laravel-cart)[![GitHub Tests Action Status](https://camo.githubusercontent.com/dce239266643645859b35dbac846b36ff948dbb99325b3d2229717673984600a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f63656e747265782f6c61726176656c2d636172742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/centrex/laravel-cart/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/5280150eaf93ee3174b750839adcaa5e3caa167be08cc66e6e551c04cad524bd/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f63656e747265782f6c61726176656c2d636172742f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/centrex/laravel-cart/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/834a99b8fb0259a5fe5a51e3528d1ab3e947e1ea5be77242be97cd48b1d0c55d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f63656e747265782f6c61726176656c2d636172743f7374796c653d666c61742d737175617265)](https://packagist.org/packages/centrex/laravel-cart)

A full-featured shopping cart for Laravel. Supports **session**, **cookie**, and **database** storage drivers, multiple named cart instances (e.g. wishlist), Livewire components (`CartIcon`, `CartDrawer`), and a REST API — all swappable via a single config key.

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

[](#installation)

```
composer require centrex/laravel-cart
php artisan vendor:publish --tag="laravel-cart-config"
```

For the database driver, run:

```
php artisan vendor:publish --tag="laravel-cart-migrations"
php artisan migrate
```

Configuration
-------------

[](#configuration)

```
php artisan vendor:publish --tag="laravel-cart-config"
```

```
// config/laravel-cart.php
'driver'          => env('CART_DRIVER', 'session'),   // session | cookie | database
'default_instance'=> 'default',
'tax'             => env('CART_TAX', 0),              // integer percent, e.g. 15
'cookie_lifetime' => env('CART_COOKIE_LIFETIME', 43200),  // minutes (default 30 days)
'database' => [
    'connection' => env('CART_DB_CONNECTION'),
    'table'      => 'carts',
],
```

### Drivers

[](#drivers)

DriverPersists across requestsAuth-awareBest for`session`Until session expiresNoDefault, server-rendered apps`cookie`30 days (configurable)NoGuest carts, headless/SPA`database`Permanently (until cleared)Yes — uses user ID for auth, session ID for guestsAuthenticated users, cart recoveryUsage
-----

[](#usage)

### Facade

[](#facade)

```
use Centrex\Cart\Facades\Cart;

// Add item (merges qty if same rowId already exists)
$item = Cart::add(
    id:      $product->id,
    name:    $product->name,
    qty:     2,
    price:   $product->price,
    options: ['color' => 'red', 'size' => 'M'],
);

echo $item->rowId;    // md5 hash of id + sorted options
echo $item->subtotal; // qty × price

// Update quantity
Cart::update($item->rowId, 5);

// Remove item
Cart::remove($item->rowId);

// Clear everything
Cart::clear();
```

### Reading the cart

[](#reading-the-cart)

```
// All items — Collection
Cart::content();

// Single item (throws CartItemNotFoundException if missing)
Cart::get($rowId);

// Aggregates
Cart::count();      // total units (sum of all qty)
Cart::lines();      // number of distinct line items
Cart::subtotal();   // sum of all item subtotals
Cart::tax();        // subtotal × (tax% / 100)
Cart::total();      // subtotal + tax
Cart::isEmpty();
```

### CartItem properties

[](#cartitem-properties)

```
$item->rowId;    // string — md5(id + sorted options)
$item->id;       // string|int — your product ID
$item->name;     // string
$item->qty;      // int
$item->price;    // float — unit price
$item->options;  // array — ['color' => 'red', 'size' => 'M']
$item->subtotal; // float — qty × price
$item->toArray();
```

### Multiple cart instances

[](#multiple-cart-instances)

Use `instance()` to work with independent named carts. Returns a new `Cart` object — does not mutate the original singleton.

```
// Default cart
Cart::add(1, 'Widget', 1, 29.99);

// Wishlist cart
$wishlist = Cart::instance('wishlist');
$wishlist->add(2, 'Gadget', 1, 99.00);

Cart::count();              // 1 (default)
$wishlist->count();         // 1 (wishlist)
```

### Events

[](#events)

Listen to cart events in your application's `EventServiceProvider`:

```
use Centrex\Cart\Events\CartItemAdded;
use Centrex\Cart\Events\CartItemUpdated;
use Centrex\Cart\Events\CartItemRemoved;
use Centrex\Cart\Events\CartCleared;

Event::listen(CartItemAdded::class, function (CartItemAdded $event) {
    // $event->item     — CartItem
    // $event->instance — 'default'
});
```

### Cookie storage — guest carts

[](#cookie-storage--guest-carts)

```
CART_DRIVER=cookie
CART_COOKIE_LIFETIME=43200  # 30 days in minutes
```

> **Note:** Cookie writes are queued for the HTTP response. A `get()` call in the same request reads what the browser already sent, not what was queued. This is standard browser behaviour.

### Database storage — persistent &amp; auth-aware

[](#database-storage--persistent--auth-aware)

```
CART_DRIVER=database
```

- Guests are identified by `session()->getId()`.
- Authenticated users are identified by `auth()->id()`.
- Cart rows are keyed on `(instance, identifier)` — unique index.

To migrate a guest cart to a user after login:

```
// In your LoginController / AuthenticatedSessionController
use Centrex\Cart\Models\StoredCart;

StoredCart::where('identifier', session()->getId())
    ->update(['identifier' => (string) auth()->id()]);
```

---

Livewire Components
-------------------

[](#livewire-components)

Requires `livewire/livewire ^3`.

### CartIcon

[](#carticon)

Displays a shopping bag icon with an item count badge. Updates automatically when the cart changes.

```
{{-- In your navbar / header --}}

```

Clicking the icon dispatches the `open-cart` browser event, which opens `CartDrawer`.

### CartDrawer

[](#cartdrawer)

A slide-out panel showing the full cart with quantity controls, item removal, and totals.

```
{{-- Once, anywhere in your layout (e.g. before ) --}}

```

Open the drawer from any element:

```
{{-- Alpine.js dispatch --}}
View Cart

{{-- Or from a Livewire component --}}
$this->dispatch('open-cart');
```

### Triggering a cart update from your own Livewire components

[](#triggering-a-cart-update-from-your-own-livewire-components)

After adding an item to the cart in a Livewire component, dispatch `cart-updated` so `CartIcon` and `CartDrawer` refresh automatically:

```
// In your ProductCard or similar Livewire component
public function addToCart(int $productId): void
{
    $product = Product::findOrFail($productId);

    Cart::add($product->id, $product->name, 1, $product->price);

    $this->dispatch('cart-updated');   // refreshes CartIcon badge + CartDrawer
    $this->dispatch('open-cart');      // optionally open the drawer
}
```

### Publish views for customisation

[](#publish-views-for-customisation)

```
php artisan vendor:publish --tag="laravel-cart-views"
# → resources/views/vendor/laravel-cart/livewire/cart-icon.blade.php
# → resources/views/vendor/laravel-cart/livewire/cart-drawer.blade.php
```

---

REST API
--------

[](#rest-api)

All endpoints are prefixed with `api` (configurable via `api_prefix`) and use the `api` middleware (configurable via `api_middleware`).

MethodEndpointDescription`GET``/api/cart`Get full cart (items, count, subtotal, tax, total)`POST``/api/cart/items`Add item to cart`PUT``/api/cart/items/{rowId}`Update item quantity`DELETE``/api/cart/items/{rowId}`Remove item`DELETE``/api/cart`Clear cart### GET /api/cart

[](#get-apicart)

```
{
  "data": {
    "instance": "default",
    "items": [
      {
        "row_id": "b8b0b1b2...",
        "id": 1,
        "name": "Widget",
        "qty": 2,
        "price": 29.99,
        "subtotal": 59.98,
        "options": { "color": "red" }
      }
    ],
    "count": 2,
    "lines": 1,
    "subtotal": 59.98,
    "tax": 0.0,
    "total": 59.98
  }
}
```

### POST /api/cart/items

[](#post-apicartitems)

```
{
  "id": 1,
  "name": "Widget",
  "qty": 2,
  "price": 29.99,
  "options": { "color": "red", "size": "M" }
}
```

### PUT /api/cart/items/{rowId}

[](#put-apicartitemsrowid)

```
{ "qty": 5 }
```

### DELETE /api/cart/items/{rowId}

[](#delete-apicartitemsrowid)

Returns `204 No Content`.

### DELETE /api/cart

[](#delete-apicart)

Returns `204 No Content`.

---

Testing
-------

[](#testing)

```
composer test        # full suite
composer test:unit   # pest only
composer test:types  # phpstan
composer lint        # pint
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Credits
-------

[](#credits)

- [rochi88](https://github.com/centrex)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance92

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 69.2% 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 ~5 days

Total

5

Last Release

38d ago

PHP version history (2 changes)v0.1.0PHP ^8.2

v0.2.0PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/29769944?v=4)[Raisul Islam](/maintainers/rochi88)[@rochi88](https://github.com/rochi88)

---

Top Contributors

[![rochi88](https://avatars.githubusercontent.com/u/29769944?v=4)](https://github.com/rochi88 "rochi88 (18 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (6 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (2 commits)")

---

Tags

laravelLaravel cartcentrex

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k51.0M7.4k](/packages/larastan-larastan)[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k89.4M569](/packages/laravel-passport)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9732.3M121](/packages/roots-acorn)[api-platform/laravel

API Platform support for Laravel

59156.3k10](/packages/api-platform-laravel)[calebdw/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

15104.9k4](/packages/calebdw-larastan)

PHPackages © 2026

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