PHPackages                             hassansin/dbcart - 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. hassansin/dbcart

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

hassansin/dbcart
================

Shopping Cart library for Laravel 5 that uses Database instead of Sessions

v1.0.0(7y ago)257.5k10[5 issues](https://github.com/hassansin/dbcart/issues)MITPHPPHP &gt;=7.1.3CI failing

Since Dec 12Pushed 7y ago4 watchersCompare

[ Source](https://github.com/hassansin/dbcart)[ Packagist](https://packagist.org/packages/hassansin/dbcart)[ Docs](https://github.com/hassansin/dbcart)[ RSS](/packages/hassansin-dbcart/feed)WikiDiscussions master Synced yesterday

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

DBCart [![Build Status](https://camo.githubusercontent.com/9850c205d2d61816ca4fb63d4e69033da1231d4b3360a515ca3ad4ffb44235e9/68747470733a2f2f7472617669732d63692e6f72672f68617373616e73696e2f6462636172742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/hassansin/dbcart) [![SensioLabsInsight](https://camo.githubusercontent.com/48dc4d49e54faad3dbffb2161edb67bff25f17abbea3d3c97fc8de5ac5fd7045/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f39373837366466382d366135312d346461312d393266332d3134656265353434633464392f6d696e692e706e673f763d31)](https://insight.sensiolabs.com/projects/97876df8-6a51-4da1-92f3-14ebe544c4d9) [![codecov](https://camo.githubusercontent.com/272e152cdb87e7ffcbe9c395ac20dbcab9b50b9638d9dd94f7496c6839c2b7e2/68747470733a2f2f636f6465636f762e696f2f67682f68617373616e73696e2f6462636172742f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/hassansin/dbcart)
======================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#dbcart------)

Shopping Cart library for Laravel 5 that uses database instead of sessions to store carts.

Features
--------

[](#features)

- Cart for guest users
- Cart for logged in users
- Guest Cart is merged with User Cart when logged in
- Singleton Cart instance to avoid unnecessary database queries. But also possible to avoid signleton cart if needed.
- Built on top of Eloquent Model, so easily extendable and all eloquent methods can be used.
- Multiple instances of cart
- Schedule expired carts for deletion

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

[](#installation)

1. Edit your project's composer.json file to require hassansin/DBCart.

    ```
    "require": {
        "hassansin/dbcart": "dev-master"
    }
    ```
2. Then install dependecies with composer command:

    ```
     composer update

    ```
3. Next, add a new provider to the providers array in config/app.php:

    ```
    'providers' => [
        //...
        Hassansin\DBCart\CartServiceProvider::class,
        //...
    ],
    ```
4. Then, publish database migrations and run migration:

    ```
    php artisan vendor:publish --provider="Hassansin\DBCart\CartServiceProvider" --tag=migrations
    php artisan migrate
    ```

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

[](#configuration)

Optionally, you can publish package config file:

```
php artisan vendor:publish --provider="Hassansin\DBCart\CartServiceProvider" --tag=config
```

Now, update `config/cart.php` if required

Usage
-----

[](#usage)

#### Get Cart Instance:

[](#get-cart-instance)

Get the current cart instance. It returns a singleton cart instance:

```
$cart = app('cart'); //using app() helper
```

or,

```
$cart = App::make('cart');
```

alternatively, you can avoid singleton instance and use the model class to load the cart instance from database everytime:

```
use Hassansin\DBCart\Models\Cart;
//...
$cart = Cart::current();
```

The idea of using singleton cart is that the cart object will be available globally throughout your app (e.g. controllers/models/views/view composers etc) for a single request. Also as you manipulate cart items, `$cart->item_count` and `$cart->total_price` would get updated.

#### Add an Item: `$cart->addItem($attributes)`

[](#add-an-item-cart-additemattributes)

```
$cart->addItem([
    'product_id' => 1,
    'unit_price' => 10.5,
    'quantity' => 1
]);
```

which is equivalent to `$cart->items()->create($attributes)`

#### Get Items: `$cart->items`

[](#get-items-cart-items)

Since `$cart` is eloquent model instance, you can use any of the eloquent methods to get items

```
$items = $cart->items // by dynamic property access
$items = $cart->items()->get()
$items = $cart->items()->where('quantity', '>=', 2)->get()
```

#### Update an Item: `$cart->updateItem($where, $attributes)`

[](#update-an-item-cart-updateitemwhere-attributes)

```
$cart->updateItem([
    'id' => 2
], [
    'product_id' => 1,
    'unit_price' => 10.5,
    'quantity' => 1
]);
```

which is equivalent to `$cart->items()->where($where)->first()->update($attributes)`

#### Remove an Item: `$cart->removeItem($where)`

[](#remove-an-item-cart-removeitemwhere)

```
$cart->removeItem([
    'id' => 2
]);
```

which is equivalent to `$cart->items()->where($where)->first()->delete()`

#### Clear Cart Items: `$cart->clear()`

[](#clear-cart-items-cart-clear)

Remove all items from the cart

```
$cart->clear();
```

#### Checkout cart: `$cart->checkout()`

[](#checkout-cart-cart-checkout)

This method only updates `status` and `placed_at` column values. `status` is set to `pending`

```
$cart->checkout();
```

#### Move item(s) between carts:

[](#move-items-between-carts)

To move all items from one cart to another cart instance:

```
$cart = app('cart');
$wishlist = app('cart', ['name' => 'wishlist']);

//move all wishlist items to cart
$wishlist->moveItemsTo($cart);
```

To move a single item between carts:

```
$cart = app('cart');
$wishlist = app('cart', ['name' => 'wishlist']);

//move an wishlist item to cart
$item = $wishlist->items()->where(['product_id' => 1])->first();
$item->moveTo($cart);
```

#### Get Cart Attributes

[](#get-cart-attributes)

```
$total_price = $cart->total_price; // cart total price
$item_count = $cart->item_count; // cart items count
$date_placed = $cart->placed_at; // returns Carbon instance
```

#### Cart Statuses

[](#cart-statuses)

Supports several cart statuses:

- `active`: currently adding items to the cart
- `expired`: cart is expired, meaningful for session carts
- `pending`: checked out carts
- `completed`: completed carts

```
use Hassansin\DBCart\Models\Cart;

// get carts based on their status: active/expired/pending/complete
$active_carts = Cart::active()->get();
$expired_carts = Cart::expired()->get();
$pending_carts = Cart::pending()->get();
$completed_carts = Cart::completed()->get();
```

#### Working with Multiple Cart Instances

[](#working-with-multiple-cart-instances)

By default, cart instances are named as `default`. You can load other instances by providing a name:

```
$cart = app('cart'); // default cart, same as: app('cart', [ 'name' => 'default'];
$sales_cart = app('cart', [ 'name' => 'sales']);
$wishlist = app('cart', [ 'name' => 'wishlist']);
```

or, without singleton carts:

```
use Hassansin\DBCart\Models\Cart;
//...
$cart = Cart::current();
$sales_cart =  Cart::current('sales');
$wishlist =  Cart::current('wishlist');
```

To get carts other than `default`:

```
$pending_sales_carts = Cart::instance('sales')->pending()->get();
```

#### Delete Expired Carts:

[](#delete-expired-carts)

The guest carts depend on the session lifetime. They are valid as long as the session is not expired. You can increase session lifetime in `config/session.php` to increase cart lifetime. When a session expires, a new cart instance will be created in database and the old one will no longer be used. Over time, these expired carts could pile-up in database.

Laravel Task Scheduler comes to the rescue. To enable scheduler just add following to the crontab in your server:

```
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

```

That's it. The module will now check for expired carts in every hour and delete them. This won't affect the carts for loggedin users.

#### Other features:

[](#other-features)

Get Cart User: `$cart->user`

Get Item Product: `$item->product`

Is Cart Empty: `$cart->isEmpty()`

If an item exists in cart: `$cart->hasItem(['id' => 10])`

Expire the cart: `cart->expire();`

Set to `completed` status: `$cart->complete();`

Extending Cart Model
--------------------

[](#extending-cart-model)

It's easy to extend DBCart. You can extend base DBCart model and add your own methods or columns. Follow these steps to extend the cart model:

1. Create a model by extending `Hassansin\DBCart\Models\Cart`:

    ```
    namespace App;

    use Hassansin\DBCart\Models\Cart as BaseCart;

    class Cart extends BaseCart
    {
        //override or add your methods here ...

        public function getSubTotalAttribute(){
            return $this->attributes['total_price'];
        }
        public function getGrandTotalAttribute(){
            //taking discount, tax etc. into account
            return $this->sub_total - $this->discount;
        }

    }
    ```
2. Update `cart_model` in `config/cart.php` with the fully qualified class name of the extended model.

    ```
    'cart_model' => App\Cart::class,
    ```
3. That's it, you can now load the cart as usual:

    ```
    $cart = App::make('cart');
    ```

You can also follow the above steps and create your own `CartLine` model by extending `Hassansin\DBCart\Models\CartLine`. Be sure to update `config/cart.php` to reflect your changes.

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance16

Infrequent updates — may be unmaintained

Popularity32

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 77.8% 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

2745d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4618044?v=4)[Hassan](/maintainers/hassansin)[@hassansin](https://github.com/hassansin)

---

Top Contributors

[![hassansin](https://avatars.githubusercontent.com/u/4618044?v=4)](https://github.com/hassansin "hassansin (7 commits)")[![vrajroham](https://avatars.githubusercontent.com/u/12662173?v=4)](https://github.com/vrajroham "vrajroham (2 commits)")

---

Tags

laraveldatabaseecommercelaravel5cartshopping cart

### Embed Badge

![Health badge](/badges/hassansin-dbcart/health.svg)

```
[![Health](https://phpackages.com/badges/hassansin-dbcart/health.svg)](https://phpackages.com/packages/hassansin-dbcart)
```

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k54.1M11.2k](/packages/illuminate-database)[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.0M90](/packages/mongodb-laravel-mongodb)[vectorial1024/laravel-cache-evict

Efficiently remove expired Laravel file/database cache data

5916.2k](/packages/vectorial1024-laravel-cache-evict)[itpathsolutions/dbstan

Database Standardization and Analysis Tool for Laravel

442.1k](/packages/itpathsolutions-dbstan)[wearepixel/laravel-cart

A cart implementation for Laravel

1355.6k](/packages/wearepixel-laravel-cart)[lemaur/eloquent-publishing

207.8k1](/packages/lemaur-eloquent-publishing)

PHPackages © 2026

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