2017 © Pedro Peláez
 

library laravel-cart-manager

Managing the cart of your Laravel application is a breeze

image

freshbitsweb/laravel-cart-manager

Managing the cart of your Laravel application is a breeze

  • Saturday, June 16, 2018
  • by gauravmak
  • Repository
  • 2 Watchers
  • 63 Stars
  • 54 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 5 Forks
  • 0 Open issues
  • 18 Versions
  • 671 % Grown

The README.md

Latest Stable Version Total Downloads License StyleCI Buy us a tree, (*1)

Cart Manager (Laravel 5.5 to Laravel 10.x)

Let's make the cart management with Laravel a breeze., (*2)

Just another shopping cart package?

There are a few well maintained shopping cart packages available but I wanted to have a solution which feels like the Laravel way and is more coupled with the database and provides additional functionality like shipping charges, discount, tax, total, round off, guest carts, etc. out-of-box while staying a very easy to use package., (*3)

Why/when to use?

Let us decide when this package should be used:, (*4)

  1. You are looking for an easy to use solution which provides cart feature for users as well as guests.
  2. You want to make sure that the carting can work via APIs as well to support mobile applications.
  3. You want features like Shipping charges, tax, discount, round off, etc.
  4. You want to store cart data in Database, session or at a custom place.
  5. You like using the packages which are more like the Laravel way

Requirements

PHP Laravel Package
8.0+ 10.x v1.6.0
8.0+ 9.x v1.5.0
7.3+ 8.x v1.4.0
<7.3 7.x v1.3.0
<7.2.5 6.x v1.2.0

Installation

1) Install the package by running this command in your terminal/cmd:, (*5)

composer require freshbitsweb/laravel-cart-manager

2) Import config file by running this command in your terminal/cmd:, (*6)

php artisan vendor:publish --tag=laravel-cart-manager-config

3) Import migrations files by running these commands in your terminal/cmd:, (*7)

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

4) Add a trait to the model(s) of cart items:, (*8)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Freshbitsweb\LaravelCartManager\Traits\Cartable;

class Product extends Model
{
    use Cartable;
    // ...
}

Usage - As Easy as 1 2 3

// Add to cart
$cart = Product::addToCart($productId);

// Remove from cart
$cart = cart()->removeAt($cartItemIndex);

// Apply discount
$cart = cart()->applyDiscount($percentage);

// Fetch cart
$cart = cart()->toArray();

Demo Repository

The repository with the demo of using this package can be found at - https://github.com/freshbitsweb/laravel-cart-manager-demo, (*9)

Table of contents

Configuration Options

cart_manager.php file contains the following config options for the package:, (*10)

  1. driver : (default: DatabaseDriver) The driver that should be used to store and retrieve cart details. You can use existing ones or create your own., (*11)

  2. auth_guard : (default: web) The authentication guard that should be used to identify the logged in customer. This package can store carts for guest users as well as logged in users., (*12)

  3. shipping_charges : (default: 10) The amount that should be applied as shipping of the order., (*13)

  4. shipping_charges_threshold : (default: 100) The minimum order amount to avoid the shipping charges. Take a note that order amount is calculated as subtotal of the cart items - discount amount., (*14)

  5. tax_percentage : (default: 6%) Tax is applied on subtotal of the cart items - discount amount + shipping charges and rounded to 2 decimals., (*15)

  6. round_off_to : (default: 0.05) You may wish to round of the order amount to the nearest decimal point. Options are (0 or 0.05 or 0.1 or 0.5 or 1), (*16)

  7. cookie_name : (default: cart_identifier) The name of the cookie that this package stores to identify the guests of the web app and store their cart data., (*17)

  8. cookie_lifetime : (default: 1 week) Number of minutes for which the cart cookie should be valid in customer's browser., (*18)

  9. LC_MONETARY : (default: en_US.UTF-8) This option is used to display the various totals of the cart with a currency symbol. We use php's native money_format() function to display currency with amount., (*19)

  10. cart_data_validity : (default: 1 week) (Database driver only) You may wish to remove old/invalid cart data from the database. You can specify the validity period and run/schedule the ClearCartDataCommand for the same., (*20)

⬆ back to top, (*21)

Drivers

You can set the driver that should be used to store and retrieve cart details in the cart_manager.php config file. You can use existing ones or create your own driver., (*22)

Database Driver

Database driver stores the cart data in 2 tables: carts and cart_items. You can also remove stale data by running ClearCartDataCommand., (*23)

Using this driver allows you to store cart data on server and customer can be displayed the same cart across channels i.e. Mobile app, website, etc., (*24)

Session Driver

This driver stores the cart data in the session according to the session driver. This driver does not support cart management for guests via API as we cannot have a uniform way to track the user., (*25)

⬆ back to top, (*26)

Cart Management

All of these operations return full cart data with items., (*27)

Add to cart

/**
 * Add to cart
 *
 * @return json
 */
 public function addToCart()
{
    return Product::addToCart(request('productId'));
}

Remove from cart

/**
 * Remove from cart
 *
 * @return json
 */
public function removeFromCart()
{
    return cart()->removeAt(request('cartItemIndex'));
}

Increment/decrement quantity of a cart item

/**
 * Increment cart item quantity
 *
 * @return json
 */
public function incrementCartItem()
{
    return cart()->incrementQuantityAt(request('cartItemIndex'));
}

/**
 * Decrement cart item quantity
 *
 * @return json
 */
public function decrementCartItem()
{
    return cart()->decrementQuantityAt(request('cartItemIndex'));
}

Update user input quantity of a cart item

/**
 * Update user input quantity.
 *
 * @return json
 */
public function cartItemQuantitySet()
{
    return cart()->setQuantityAt(request('cartItemIndex'), request('cartQuantity'));
}

Clear cart

/**
 * Clear Cart
 *
 * @return json
 */
public function clearCart()
{
    return cart()->clear();
}

⬆ back to top, (*28)

Fetching Cart Data

Get complete cart details

$cart = cart()->toArray();

Get cart attributes

$cartAttributes = cart()->data();

Get cart attributes with currency amount

$cartTotals = cart()->totals();

Get cart individual attributes

Cart has following attributes: subtotal, discount, discountPercentage, couponId, shippingCharges, netTotal, tax, total, roundOff, payable., (*29)

You can access any of them using a getter method. For example,, (*30)

$subtotal = cart()->getSubtotal();

Get cart items

$cartItems = cart()->items();

Get cart items with currency amount

$cartItems = cart()->items($displayCurrency = true);

, (*31)

⬆ back to top, (*32)

Discounts

Apply percentage discount

$cart = cart()->applyDiscount($percentage);

Apply flat discount

$cart = cart()->applyFlatDiscount($discountAmount);

, (*33)

⬆ back to top, (*34)

Updates in Item Prices

As this package stores the details of the cart items in a separate table or session, the cart data will not be updated if you update, price, name or image of the cart items., (*35)

If you update any of the item details regularly, we suggest you to run the following code before the final checkout to make sure that order totals are up-to-date as per the latest prices., (*36)

cart()->refreshAllItemsData();

This code will go through each cart item and update to fresh details., (*37)

⬆ back to top, (*38)

Using With API

Note: This feature is for Database driver only., (*39)

This package uses the cookies and sessions to maintain cart data during page reloads. As the APIs are stateless, we cannot use them to do the same., (*40)

To solve the issue, you can manually set the authenticated user id to maintain the cart data., (*41)

cart()->setUser($userId);

Running this code will tell the package to assign the cart data to the specified user., (*42)

Note: Guests cannot manage their carts via API as we cannot have a uniform way to track the user., (*43)

⬆ back to top, (*44)

Events

Working with Laravel, how can we forget events?, (*45)

This package fires various cart related events which you can listen to for any application updates., (*46)

  1. CartCreated -> Fired when cart is created for the session for the first time and contains the full cart data in the variable $cartData., (*47)

  2. CartItemAdded -> Fired when an item is added to the cart and contains the new item Eloquent model object in the variable $entity., (*48)

  3. CartItemRemoved -> Fired when an item is removed from the cart and contains the new item Eloquent model object in the variable $entity., (*49)

  4. DiscountApplied -> Fired when discount if applied to the cart and contains the full cart data in the variable $cartData., (*50)

  5. CartCleared -> Fired when the cart is cleared., (*51)

Sample Usage

Add the event and listener entry in the EventServiceProvider class, (*52)

protected $listen = [
    'Freshbitsweb\LaravelCartManager\Events\CartCreated' => [
        'App\Listeners\LogCartCreated',
    ],
];

Create respective listener:, (*53)

<?php

namespace App\Listeners;

use Illuminate\Support\Facades\Log;
use Freshbitsweb\LaravelCartManager\Events\CartCreated;

class LogCartCreated
{
    /**
     * Handle the event.
     *
     * @param CartCreated $event
     * @return void
     */
    public function handle(CartCreated  $event)
    {
        Log::info('cart', [$event->cartData]);
    }
}

⬆ back to top, (*54)

Commands

Note: This is required for Database driver only., (*55)

You may wish to remove old/invalid cart data from the database., (*56)

Schedule the ClearCartDataCommand for the same., (*57)

protected function schedule(Schedule $schedule)
{
    $schedule->command('lcm_carts:clear_old')->daily();
}

This will delete the old/invalid data which is considered based on the cart_data_validity config option., (*58)

⬆ back to top, (*59)

Tests

Run this command to run the tests of the package:, (*60)

composer test

Authors

See also the list of contributors who participated in this project., (*61)

⬆ back to top, (*62)

License

This project is licensed under the MIT License - see the LICENSE file for details, (*63)

Treeware

You're free to use this package, but if it makes it to your production environment I would highly appreciate you buying the world a tree., (*64)

It’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to plant trees. If you contribute to our forest you’ll be creating employment for local families and restoring wildlife habitats., (*65)

You can buy trees at for our forest here offset.earth/treeware, (*66)

Read more about Treeware at treeware.earth, (*67)

Special Thanks to

The Versions

16/06 2018

dev-master

9999999-dev

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

The Development Requires

by Gaurav Makhecha

13/06 2018

v1.0.15

1.0.15.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

The Development Requires

by Gaurav Makhecha

01/06 2018

v1.0.14

1.0.14.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

The Development Requires

by Gaurav Makhecha

05/05 2018

dev-analysis-XNadPp

dev-analysis-XNadPp

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

03/05 2018

v1.0.13

1.0.13.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

17/04 2018

v1.0.12

1.0.12.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

16/04 2018

v1.0.11

1.0.11.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

11/04 2018

v1.0.10

1.0.10.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

07/04 2018

v1.0.9

1.0.9.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

07/04 2018

v1.0.8

1.0.8.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

21/02 2018

v1.0.7

1.0.7.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

26/01 2018

v1.0.6

1.0.6.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

26/01 2018

v1.0.5

1.0.5.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

30/12 2017

v1.0.4

1.0.4.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

30/12 2017

v1.0.3

1.0.3.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

29/12 2017

v1.0.2

1.0.2.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

27/12 2017

v1.0.1

1.0.1.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha

23/12 2017

v1.0.0

1.0.0.0

Managing the cart of your Laravel application is a breeze

  Sources   Download

MIT

The Requires

 

by Gaurav Makhecha