Giter Site home page Giter Site logo

freshbitsweb / laravel-cart-manager Goto Github PK

View Code? Open in Web Editor NEW
229.0 11.0 32.0 157 KB

Managing the cart in your Laravel/E-commerce application is a breeze

License: MIT License

PHP 100.00%
php7 laravel laravel-5-package laravel-shopping-cart cart-manager ecommerce laravel-6-package shopping-cart shipping-charges cart-data

laravel-cart-manager's Introduction

Latest Stable Version Total Downloads License StyleCI Buy us a tree

Cart Manager (Laravel 5.5 to Laravel 10.x)

Let's make the cart management with Laravel a breeze.

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.

Why/when to use?

Let us decide when this package should be used:

  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:
composer require freshbitsweb/laravel-cart-manager
  1. Import config file by running this command in your terminal/cmd:
php artisan vendor:publish --tag=laravel-cart-manager-config
  1. Import migrations files by running these commands in your terminal/cmd:
php artisan vendor:publish --tag=laravel-cart-manager-migrations
php artisan migrate
  1. Add a trait to the model(s) of cart items:
<?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

Table of contents

Configuration Options

cart_manager.php file contains the following config options for the package:

  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.

  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.

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

  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.

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

  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)

  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.

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

  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.

  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.

⬆ back to top

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.

Database Driver

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

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.

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.

⬆ back to top

Cart Management

All of these operations return full cart data with items.

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

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.

You can access any of them using a getter method. For example,

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

Get cart items

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

Get cart items with currency amount

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

⬆ back to top

Discounts

Apply percentage discount

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

Apply flat discount

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

⬆ back to top

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.

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.

cart()->refreshAllItemsData();

This code will go through each cart item and update to fresh details.

⬆ back to top

Using With API

Note: This feature is for Database driver only.

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.

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

cart()->setUser($userId);

Running this code will tell the package to assign the cart data to the specified user.

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

⬆ back to top

Events

Working with Laravel, how can we forget events?

This package fires various cart related events which you can listen to for any application updates.

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

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

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

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

  5. CartCleared -> Fired when the cart is cleared.

Sample Usage

Add the event and listener entry in the EventServiceProvider class

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

Create respective listener:

<?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

Commands

Note: This is required for Database driver only.

You may wish to remove old/invalid cart data from the database.

Schedule the ClearCartDataCommand for the same.

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.

⬆ back to top

Tests

Run this command to run the tests of the package:

composer test

Authors

See also the list of contributors who participated in this project.

⬆ back to top

License

This project is licensed under the MIT License - see the LICENSE file for details

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.

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.

You can buy trees at for our forest here offset.earth/treeware

Read more about Treeware at treeware.earth

Special Thanks to

laravel-cart-manager's People

Contributors

ankurk91 avatar dylan-dpc avatar gauravmak avatar hirenkeraliya avatar jamesmills avatar laravel-shift avatar rajan-parmar avatar stylecibot avatar utsavsomaiya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-cart-manager's Issues

instalation on laravel 6 for api (guard name = api)

not installing this error is showing on composer require freshbitsweb/laravel-cart-manager.

error

In CartManagerServiceProvider.php line 49:

Trying to access array offset on value of type null ,

Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Installation failed, reverting ./composer.json to its original content.

Performance issue duplicate query when use cart() helper

Describe the bug
cart() helper hit database query every time.
example:
protected function getCartDetails() { return [ 'items' => cart()->items($displayCurrency = true), 'totals' => cart()->totals(), ]; }
This function will hit database multiple times.
To Reproduce
Steps to reproduce the behavior:

  1. Clone demo
  2. Install debugbar
  3. We will see duplicate query

Expected behavior
No duplicate query during request

Screenshots
1

Additional context
Suguest fix: Change bind to singleton in CartManagerServiceProvider

User input to update cart quantity

Is your feature request related to a problem? Please describe.
If the user want to update the cartItems quantity at big number, it's good to have a method to update the quantity with input instead of one by one.

Describe the solution you'd like

/**
     * Set the quantity of a cart item.
     *
     * @param int Index of the cart item
     * @param int quantity to be increased
     * @return array
     */
    public function setQuantityAt($cartItemIndex, $quantity = 1)
    {
        $this->existenceCheckFor($cartItemIndex);

        $this->items[$cartItemIndex]->quantity = $quantity;

        $this->cartDriver->setCartItemQuantity(
            $this->items[$cartItemIndex]->id,
            $this->items[$cartItemIndex]->quantity
        );

        return $this->cartUpdates();
    }

Describe alternatives you've considered
Add a new method in CartItemsManager to let user update the quantity

Remove specific product in all users carts

Is your feature request related to a problem? Please describe.
Let's say a product is no longer available. It has to be removed from all carts immediately so that users' won't buy those items.

Describe the solution you'd like
From the documentation, I cannot find how to update all users' carts with the available methods. Does cart() method apply to all users or just the current user?

Describe alternatives you've considered
I tried fetching all carts that include the given product id. After that, I check the carts but I can't find a way to remove and update the totals etc.

Undefined function money_format()

Describe the bug
A clear and concise description of what the bug is.

I'm using your official repository demo project. I'm installing packages, setup .env config & startup local server using Laravel server php artisan serve, but I get on root page next error from Laravel.
Call to undefined function Freshbitsweb\LaravelCartManager\Core\money_format()

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.
image

Additional context
Add any other context about the problem here.

incrementQuantityAt There is no item in the cart at the specified index.

protected function existenceCheckFor($cartItemIndex)
{
    if (! $this->items->has($cartItemIndex)) {
        throw new ItemMissing('There is no item in the cart at the specified index.');
    }
}

Why do I always get false? Where does has() function come from?
$this->items returns array of object, doesn't it?
And $cartItemIndex is id column of cart_items table, isn't it?

Merging existing cart with guest made cart

I'm looking for a way to merge the carts when a guest logs in to their existing account, with a guest cart active, and already some cart Items that are added when the user was previous logged in.

Is this something that is already considered?

Laravel 8 Support

Is your feature request related to a problem? Please describe.
I cannot upgrade my app to Laravel 8, please update your composer.json dependency file

Describe the solution you'd like
Add Laravel 8, to your composer.json dependency file

Describe alternatives you've considered
None

Additional context
None

How to update the card

Hello, I have a question. I want to add a coupon id to the card but I can't. How do I add a coupon id and update my card?

configuration options

Change in configuration options

I want to apply 0% tax. I have updated in cart_manager.php at following lines

'tax_percentage' => 0,

but still it gives 6% tax

can you please tell how i can make tax 0% and shipping 0% and other configurations 0%

thanks

Can't update or remove cart item, no item at specified index

i attempt to update and remove the cart items, but it's not working, the error message says "There is no item in the cart at the specified index" but i'm sure the index is exist in db.

the error message

"msg": "Cant remove at index 12",
    "detail": "Freshbitsweb\\LaravelCartManager\\Exceptions\\ItemMissing: There is no item in the cart at the specified index....

my composer.json

"php": "^7.1.3",
"freshbitsweb/laravel-cart-manager": "^1.2",
"laravel/framework": "6.0.*",
"laravel/passport": "^8.0",

my cart config

return [
    // The driver that should be used to manage the cart (database/session/custom)
    'driver' => Freshbitsweb\LaravelCartManager\Drivers\DatabaseDriver::class,

    // The authentication guard that should be used to identify the logged in customer
    'auth_guard' => 'api',

    // Shipping charges are applied on order amount (subtotal - discount)
    'shipping_charges' => 0,

    // Specify the minimum order amount to avoid shipping charges
    'shipping_charges_threshold' => 0,

    // Tax amount is applied on net total (subtotal - discount + shipping charges)
    // subtotal, tax, net total and total are rounded to 2 decimals
    'tax_percentage' => 0,

    // Round off the total amount (net total + tax) to nearest (0 or 0.05 or 0.1 or 0.5 or 1)
    // Total amount is rounded off accordingly to come up the payable amount by the customer
    'round_off_to' => 0,

    // Name of the cookie that is used to identify a user session
    'cookie_name' => 'cart_identifier',

    // Number of minutes for which the cart cookie should be valid in user's browser
    'cookie_lifetime' => 10080, // one week

    // We use php's NumberFormatter class to display numbers as a currency value
    // Ref - https://www.php.net/manual/en/class.numberformatter.php
    // Locales list - https://stackoverflow.com/a/3191729/3113599
    'locale' => 'en_US',

    // Currency to display numbers with symbols - The 3-letter ISO 4217 currency code
    'currency' => 'IDR',

    // For Database driver only: Number of hours for which the cart data is considered valid
    // You can run/schedule the lcm_cart:clear command to remove old/invalid data
    'cart_data_validity' => 24 * 7, // a week
    ];

this is my delete function in controller

public function delete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'cartid' => 'required | exists:carts,auth_user',
            'item_id' => 'required | integer | exists:cart_items,id',
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => 'Gagal mendapatkan keranjang belanja!'], 442);exit;
        }
        
        // set user to cart
        $cart = cart()->setUser($request->cartid);
        try {
            // trying to remove item
            $cart = cart()->removeAt($request->item_id);
            return response()->json(['cart' => $cart, 'cart_id' => $request->cartid], 200);
        } catch (\Throwable $th) {
            return response()->json(['msg' => 'Cant remove at index '.$request->item_id, 'detail' => ''.$th,'cart_id' => $request->cartid, 'cart_items' => cart()->toArray()], 200);
        }
    }

at last, this is my sample response (get all items from cart)

"cart_items": {
        "subtotal": "2.00",
        "discount": "0.00",
        "discountPercentage": "0.00",
        "couponId": null,
        "shippingCharges": "0.00",
        "netTotal": "2.00",
        "tax": "0.00",
        "total": "2.00",
        "roundOff": "0.00",
        "payable": "2.00",
        "items": [
            {
                "modelType": "App\\Product",
                "modelId": 7,
                "name": "Autem aut voluptas e",
                "price": "1.00",
                "image": "/userfile/5/Selection_006.png",
                "quantity": 1,
                "id": 9
            },
            {
                "modelType": "App\\Product",
                "modelId": 8,
                "name": "asdasdff",
                "price": "1.00",
                "image": "/userfile/5/Selection_006.png",
                "quantity": 1,
                "id": 12
            }
        ]
    }

in the response above, i have 1 item with id of 12, but still i have this error no item at specified index 12

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.