GithubHelp home page GithubHelp logo

darryldecode / laravelshoppingcart Goto Github PK

View Code? Open in Web Editor NEW
1.3K 53.0 434.0 307 KB

Shopping Cart Implementation for Laravel Framework

PHP 100.00%
laravel laravel-shopping-cart shopping-cart laravel-cart laravel-5-cart laravel-5-shoppingcart laravel-5-shopping-cart

laravelshoppingcart's Introduction

Laravel 5 & 6 , 7 & 9 Shopping Cart

Build Status Total Downloads License

A Shopping Cart Implementation for Laravel Framework

QUICK PARTIAL DEMO

Demo: https://shoppingcart-demo.darrylfernandez.com/cart

Git repo of the demo: https://github.com/darryldecode/laravelshoppingcart-demo

INSTALLATION

Install the package through Composer.

For Laravel 5.1~: composer require "darryldecode/cart:~2.0"

For Laravel 5.5, 5.6, or 5.7~, 9:

composer require "darryldecode/cart:~4.0" or composer require "darryldecode/cart"

CONFIGURATION

  1. Open config/app.php and add this line to your Service Providers Array.
Darryldecode\Cart\CartServiceProvider::class
  1. Open config/app.php and add this line to your Aliases
  'Cart' => Darryldecode\Cart\Facades\CartFacade::class
  1. Optional configuration file (useful if you plan to have full control)
php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="config"

HOW TO USE

Quick Usage Example

// Quick Usage with the Product Model Association & User session binding

$Product = Product::find($productId); // assuming you have a Product model with id, name, description & price
$rowId = 456; // generate a unique() row ID
$userID = 2; // the user ID to bind the cart contents

// add the product to cart
\Cart::session($userID)->add(array(
    'id' => $rowId,
    'name' => $Product->name,
    'price' => $Product->price,
    'quantity' => 4,
    'attributes' => array(),
    'associatedModel' => $Product
));

// update the item on cart
\Cart::session($userID)->update($rowId,[
	'quantity' => 2,
	'price' => 98.67
]);

// delete an item on cart
\Cart::session($userID)->remove($rowId);

// view the cart items
$items = \Cart::getContent();
foreach($items as $row) {

	echo $row->id; // row ID
	echo $row->name;
	echo $row->qty;
	echo $row->price;
	
	echo $item->associatedModel->id; // whatever properties your model have
        echo $item->associatedModel->name; // whatever properties your model have
        echo $item->associatedModel->description; // whatever properties your model have
}

// FOR FULL USAGE, SEE BELOW..

Usage

IMPORTANT NOTE!

By default, the cart has a default sessionKey that holds the cart data. This also serves as a cart unique identifier which you can use to bind a cart to a specific user. To override this default session Key, you will just simply call the \Cart::session($sessionKey) method BEFORE ANY OTHER METHODS!!.

Example:

$userId // the current login user id

// This tells the cart that we only need or manipulate
// the cart data of a specific user. It doesn't need to be $userId,
// you can use any unique key that represents a unique to a user or customer.
// basically this binds the cart to a specific user.
\Cart::session($userId);

// then followed by the normal cart usage
\Cart::add();
\Cart::update();
\Cart::remove();
\Cart::condition($condition1);
\Cart::getTotal();
\Cart::getSubTotal();
\Cart::getSubTotalWithoutConditions();
\Cart::addItemCondition($productID, $coupon101);
// and so on..

See More Examples below:

Adding Item on Cart: Cart::add()

There are several ways you can add items on your cart, see below:

/**
 * add item to the cart, it can be an array or multi dimensional array
 *
 * @param string|array $id
 * @param string $name
 * @param float $price
 * @param int $quantity
 * @param array $attributes
 * @param CartCondition|array $conditions
 * @return $this
 * @throws InvalidItemException
 */

 # ALWAYS REMEMBER TO BIND THE CART TO A USER BEFORE CALLING ANY CART FUNCTION
 # SO CART WILL KNOW WHO'S CART DATA YOU WANT TO MANIPULATE. SEE IMPORTANT NOTICE ABOVE.
 # EXAMPLE: \Cart::session($userId); then followed by cart normal usage.
 
 # NOTE:
 # the 'id' field in adding a new item on cart is not intended for the Model ID (example Product ID)
 # instead make sure to put a unique ID for every unique product or product that has it's own unique prirce, 
 # because it is used for updating cart and how each item on cart are segregated during calculation and quantities. 
 # You can put the model_id instead as an attribute for full flexibility.
 # Example is that if you want to add same products on the cart but with totally different attribute and price.
 # If you use the Product's ID as the 'id' field in cart, it will result to increase in quanity instead
 # of adding it as a unique product with unique attribute and price.

// Simplest form to add item on your cart
Cart::add(455, 'Sample Item', 100.99, 2, array());

// array format
Cart::add(array(
    'id' => 456, // inique row ID
    'name' => 'Sample Item',
    'price' => 67.99,
    'quantity' => 4,
    'attributes' => array()
));

// add multiple items at one time
Cart::add(array(
  array(
      'id' => 456,
      'name' => 'Sample Item 1',
      'price' => 67.99,
      'quantity' => 4,
      'attributes' => array()
  ),
  array(
      'id' => 568,
      'name' => 'Sample Item 2',
      'price' => 69.25,
      'quantity' => 4,
      'attributes' => array(
        'size' => 'L',
        'color' => 'blue'
      )
  ),
));

// add cart items to a specific user
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->add(array(
    'id' => 456, // inique row ID
    'name' => 'Sample Item',
    'price' => 67.99,
    'quantity' => 4,
    'attributes' => array(),
    'associatedModel' => $Product
));

// NOTE:
// Please keep in mind that when adding an item on cart, the "id" should be unique as it serves as
// row identifier as well. If you provide same ID, it will assume the operation will be an update to its quantity
// to avoid cart item duplicates

Updating an item on a cart: Cart::update()

Updating an item on a cart is very simple:

/**
 * update a cart
 *
 * @param $id (the item ID)
 * @param array $data
 *
 * the $data will be an associative array, you don't need to pass all the data, only the key value
 * of the item you want to update on it
 */

Cart::update(456, array(
  'name' => 'New Item Name', // new item name
  'price' => 98.67, // new item price, price can also be a string format like so: '98.67'
));

// you may also want to update a product's quantity
Cart::update(456, array(
  'quantity' => 2, // so if the current product has a quantity of 4, another 2 will be added so this will result to 6
));

// you may also want to update a product by reducing its quantity, you do this like so:
Cart::update(456, array(
  'quantity' => -1, // so if the current product has a quantity of 4, it will subtract 1 and will result to 3
));

// NOTE: as you can see by default, the quantity update is relative to its current value
// if you want to just totally replace the quantity instead of incrementing or decrementing its current quantity value
// you can pass an array in quantity value like so:
Cart::update(456, array(
  'quantity' => array(
      'relative' => false,
      'value' => 5
  ),
));
// so with that code above as relative is flagged as false, if the item's quantity before is 2 it will now be 5 instead of
// 5 + 2 which results to 7 if updated relatively..

// updating a cart for a specific user
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->update(456, array(
  'name' => 'New Item Name', // new item name
  'price' => 98.67, // new item price, price can also be a string format like so: '98.67'
));

Removing an item on a cart: Cart::remove()

Removing an item on a cart is very easy:

/**
 * removes an item on cart by item ID
 *
 * @param $id
 */

Cart::remove(456);

// removing cart item for a specific user's cart
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->remove(456);

Getting an item on a cart: Cart::get()

/**
 * get an item on a cart by item ID
 * if item ID is not found, this will return null
 *
 * @param $itemId
 * @return null|array
 */

$itemId = 456;

Cart::get($itemId);

// You can also get the sum of the Item multiplied by its quantity, see below:
$summedPrice = Cart::get($itemId)->getPriceSum();

// get an item on a cart by item ID for a specific user's cart
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->get($itemId);

Getting cart's contents and count: Cart::getContent()

/**
 * get the cart
 *
 * @return CartCollection
 */

$cartCollection = Cart::getContent();

// NOTE: Because cart collection extends Laravel's Collection
// You can use methods you already know about Laravel's Collection
// See some of its method below:

// count carts contents
$cartCollection->count();

// transformations
$cartCollection->toArray();
$cartCollection->toJson();

// Getting cart's contents for a specific user
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->getContent($itemId);

Check if cart is empty: Cart::isEmpty()

/**
* check if cart is empty
*
* @return bool
*/
Cart::isEmpty();

// Check if cart's contents is empty for a specific user
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->isEmpty();

Get cart total quantity: Cart::getTotalQuantity()

/**
* get total quantity of items in the cart
*
* @return int
*/
$cartTotalQuantity = Cart::getTotalQuantity();

// for a specific user
$cartTotalQuantity = Cart::session($userId)->getTotalQuantity();

Get cart subtotal: Cart::getSubTotal()

/**
* get cart sub total
*
* @return float
*/
$subTotal = Cart::getSubTotal();

// for a specific user
$subTotal = Cart::session($userId)->getSubTotal();

Get cart subtotal with out conditions: Cart::getSubTotalWithoutConditions()

/**
* get cart sub total with out conditions
*
* @param bool $formatted
* @return float
*/
$subTotalWithoutConditions = Cart::getSubTotalWithoutConditions();

// for a specific user
$subTotalWithoutConditions = Cart::session($userId)->getSubTotalWithoutConditions();

Get cart total: Cart::getTotal()

/**
 * the new total in which conditions are already applied
 *
 * @return float
 */
$total = Cart::getTotal();

// for a specific user
$total = Cart::session($userId)->getTotal();

Clearing the Cart: Cart::clear()

/**
* clear cart
*
* @return void
*/
Cart::clear();
Cart::session($userId)->clear();

Conditions

Laravel Shopping Cart supports cart conditions. Conditions are very useful in terms of (coupons,discounts,sale,per-item sale and discounts etc.) See below carefully on how to use conditions.

Conditions can be added on:

1.) Whole Cart Value bases

2.) Per-Item Bases

First let's add a condition on a Cart Bases:

There are also several ways of adding a condition on a cart: NOTE:

When adding a condition on a cart bases, the 'target' should have value of 'subtotal' or 'total'. If the target is "subtotal" then this condition will be applied to subtotal. If the target is "total" then this condition will be applied to total. The order of operation also during calculation will vary on the order you have added the conditions.

Also, when adding conditions, the 'value' field will be the bases of calculation. You can change this order by adding 'order' parameter in CartCondition.

// add single condition on a cart bases
$condition = new \Darryldecode\Cart\CartCondition(array(
    'name' => 'VAT 12.5%',
    'type' => 'tax',
    'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
    'value' => '12.5%',
    'attributes' => array( // attributes field is optional
    	'description' => 'Value added tax',
    	'more_data' => 'more data here'
    )
));

Cart::condition($condition);
Cart::session($userId)->condition($condition); // for a speicifc user's cart

// or add multiple conditions from different condition instances
$condition1 = new \Darryldecode\Cart\CartCondition(array(
    'name' => 'VAT 12.5%',
    'type' => 'tax',
    'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
    'value' => '12.5%',
    'order' => 2
));
$condition2 = new \Darryldecode\Cart\CartCondition(array(
    'name' => 'Express Shipping $15',
    'type' => 'shipping',
    'target' => 'subtotal', // this condition will be applied to cart's subtotal when getSubTotal() is called.
    'value' => '+15',
    'order' => 1
));
Cart::condition($condition1);
Cart::condition($condition2);

// Note that after adding conditions that are targeted to be applied on subtotal, the result on getTotal()
// will also be affected as getTotal() depends in getSubTotal() which is the subtotal.

// add condition to only apply on totals, not in subtotal
$condition = new \Darryldecode\Cart\CartCondition(array(
    'name' => 'Express Shipping $15',
    'type' => 'shipping',
    'target' => 'total', // this condition will be applied to cart's total when getTotal() is called.
    'value' => '+15',
    'order' => 1 // the order of calculation of cart base conditions. The bigger the later to be applied.
));
Cart::condition($condition);

// The property 'order' lets you control the sequence of conditions when calculated. Also it lets you add different conditions through for example a shopping process with multiple
// pages and still be able to set an order to apply the conditions. If no order is defined defaults to 0

// NOTE!! On current version, 'order' parameter is only applicable for conditions for cart bases. It does not support on per item conditions.

// or add multiple conditions as array
Cart::condition([$condition1, $condition2]);

// To get all applied conditions on a cart, use below:
$cartConditions = Cart::getConditions();
foreach($cartConditions as $condition)
{
    $condition->getTarget(); // the target of which the condition was applied
    $condition->getName(); // the name of the condition
    $condition->getType(); // the type
    $condition->getValue(); // the value of the condition
    $condition->getOrder(); // the order of the condition
    $condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added
}

// You can also get a condition that has been applied on the cart by using its name, use below:
$condition = Cart::getCondition('VAT 12.5%');
$condition->getTarget(); // the target of which the condition was applied
$condition->getName(); // the name of the condition
$condition->getType(); // the type
$condition->getValue(); // the value of the condition
$condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added

// You can get the conditions calculated value by providing the subtotal, see below:
$subTotal = Cart::getSubTotal();
$condition = Cart::getCondition('VAT 12.5%');
$conditionCalculatedValue = $condition->getCalculatedValue($subTotal);

NOTE: All cart based conditions should be added to cart's conditions before calling Cart::getTotal() and if there are also conditions that are targeted to be applied to subtotal, it should be added to cart's conditions before calling Cart::getSubTotal()

$cartTotal = Cart::getSubTotal(); // the subtotal with the conditions targeted to "subtotal" applied
$cartTotal = Cart::getTotal(); // the total with the conditions targeted to "total" applied
$cartTotal = Cart::session($userId)->getSubTotal(); // for a specific user's cart
$cartTotal = Cart::session($userId)->getTotal(); // for a specific user's cart

Next is the Condition on Per-Item Bases.

This is very useful if you have coupons to be applied specifically on an item and not on the whole cart value.

NOTE: When adding a condition on a per-item bases, the 'target' parameter is not needed or can be omitted. unlike when adding conditions or per cart bases.

Now let's add condition on an item.

// lets create first our condition instance
$saleCondition = new \Darryldecode\Cart\CartCondition(array(
            'name' => 'SALE 5%',
            'type' => 'tax',
            'value' => '-5%',
        ));

// now the product to be added on cart
$product = array(
            'id' => 456,
            'name' => 'Sample Item 1',
            'price' => 100,
            'quantity' => 1,
            'attributes' => array(),
            'conditions' => $saleCondition
        );

// finally add the product on the cart
Cart::add($product);

// you may also add multiple condition on an item
$itemCondition1 = new \Darryldecode\Cart\CartCondition(array(
    'name' => 'SALE 5%',
    'type' => 'sale',
    'value' => '-5%',
));
$itemCondition2 = new CartCondition(array(
    'name' => 'Item Gift Pack 25.00',
    'type' => 'promo',
    'value' => '-25',
));
$itemCondition3 = new \Darryldecode\Cart\CartCondition(array(
    'name' => 'MISC',
    'type' => 'misc',
    'value' => '+10',
));

$item = array(
          'id' => 456,
          'name' => 'Sample Item 1',
          'price' => 100,
          'quantity' => 1,
          'attributes' => array(),
          'conditions' => [$itemCondition1, $itemCondition2, $itemCondition3]
      );

Cart::add($item);

NOTE: All cart per-item conditions should be added before calling Cart::getSubTotal()

Then Finally you can call Cart::getSubTotal() to get the Cart sub total with the applied conditions on each of the items.

// the subtotal will be calculated based on the conditions added that has target => "subtotal"
// and also conditions that are added on per item
$cartSubTotal = Cart::getSubTotal();

Add condition to existing Item on the cart: Cart::addItemCondition($productId, $itemCondition)

Adding Condition to an existing Item on the cart is simple as well.

This is very useful when adding new conditions on an item during checkout process like coupons and promo codes. Let's see the example how to do it:

$productID = 456;
$coupon101 = new CartCondition(array(
            'name' => 'COUPON 101',
            'type' => 'coupon',
            'value' => '-5%',
        ));

Cart::addItemCondition($productID, $coupon101);

Clearing Cart Conditions: Cart::clearCartConditions()

/**
* clears all conditions on a cart,
* this does not remove conditions that has been added specifically to an item/product.
* If you wish to remove a specific condition to a product, you may use the method: removeItemCondition($itemId,$conditionName)
*
* @return void
*/
Cart::clearCartConditions()

Remove Specific Cart Condition: Cart::removeCartCondition($conditionName)

/**
* removes a condition on a cart by condition name,
* this can only remove conditions that are added on cart bases not conditions that are added on an item/product.
* If you wish to remove a condition that has been added for a specific item/product, you may
* use the removeItemCondition(itemId, conditionName) method instead.
*
* @param $conditionName
* @return void
*/
$conditionName = 'Summer Sale 5%';

Cart::removeCartCondition($conditionName)

Remove Specific Item Condition: Cart::removeItemCondition($itemId, $conditionName)

/**
* remove a condition that has been applied on an item that is already on the cart
*
* @param $itemId
* @param $conditionName
* @return bool
*/
Cart::removeItemCondition($itemId, $conditionName)

Clear all Item Conditions: Cart::clearItemConditions($itemId)

/**
* remove all conditions that has been applied on an item that is already on the cart
*
* @param $itemId
* @return bool
*/
Cart::clearItemConditions($itemId)

Get conditions by type: Cart::getConditionsByType($type)

/**
* Get all the condition filtered by Type
* Please Note that this will only return condition added on cart bases, not those conditions added
* specifically on an per item bases
*
* @param $type
* @return CartConditionCollection
*/
public function getConditionsByType($type)

Remove conditions by type: Cart::removeConditionsByType($type)

/**
* Remove all the condition with the $type specified
* Please Note that this will only remove condition added on cart bases, not those conditions added
* specifically on an per item bases
*
* @param $type
* @return $this
*/
public function removeConditionsByType($type)

Items

The method Cart::getContent() returns a collection of items.

To get the id of an item, use the property $item->id.

To get the name of an item, use the property $item->name.

To get the quantity of an item, use the property $item->quantity.

To get the attributes of an item, use the property $item->attributes.

To get the price of a single item without the conditions applied, use the property $item->price.

To get the subtotal of an item without the conditions applied, use the method $item->getPriceSum().

/**
* get the sum of price
*
* @return mixed|null
*/
public function getPriceSum()

To get the price of a single item without the conditions applied, use the method

$item->getPriceWithConditions().

/**
* get the single price in which conditions are already applied
*
* @return mixed|null
*/
public function getPriceWithConditions()

To get the subtotal of an item with the conditions applied, use the method

$item->getPriceSumWithConditions()

/**
* get the sum of price in which conditions are already applied
*
* @return mixed|null
*/
public function getPriceSumWithConditions()

NOTE: When you get price with conditions applied, only the conditions assigned to the current item will be calculated. Cart conditions won't be applied to price.

Associating Models

One can associate a cart item to a model. 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 using the property $item->model.

Here is an example:

// add the item to the cart.
$cartItem = Cart::add(455, 'Sample Item', 100.99, 2, array())->associate('Product');

// array format
Cart::add(array(
    'id' => 456,
    'name' => 'Sample Item',
    'price' => 67.99,
    'quantity' => 4,
    'attributes' => array(),
    'associatedModel' => 'Product'
));

// add multiple items at one time
Cart::add(array(
  array(
      'id' => 456,
      'name' => 'Sample Item 1',
      'price' => 67.99,
      'quantity' => 4,
      'attributes' => array(),
      'associatedModel' => 'Product'
  ),
  array(
      'id' => 568,
      'name' => 'Sample Item 2',
      'price' => 69.25,
      'quantity' => 4,
      'attributes' => array(
        'size' => 'L',
        'color' => 'blue'
      ),
      'associatedModel' => 'Product'
  ),
));

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

NOTE: This only works when adding an item to cart.

Instances

You may also want multiple cart instances on the same page without conflicts. To do that,

Create a new Service Provider and then on register() method, you can put this like so:

$this->app['wishlist'] = $this->app->share(function($app)
		{
			$storage = $app['session']; // laravel session storage
			$events = $app['events']; // laravel event handler
			$instanceName = 'wishlist'; // your cart instance name
			$session_key = 'AsASDMCks0ks1'; // your unique session key to hold cart items

			return new Cart(
				$storage,
				$events,
				$instanceName,
				$session_key
			);
		});

// for 5.4 or newer
use Darryldecode\Cart\Cart;
use Illuminate\Support\ServiceProvider;

class WishListProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('wishlist', function($app)
        {
            $storage = $app['session'];
            $events = $app['events'];
            $instanceName = 'cart_2';
            $session_key = '88uuiioo99888';
            return new Cart(
                $storage,
                $events,
                $instanceName,
                $session_key,
                config('shopping_cart')
            );
        });
    }
}

IF you are having problem with multiple cart instance, please see the codes on this demo repo here: DEMO

Exceptions

There are currently only two exceptions.

Exception Description
InvalidConditionException When there is an invalid field value during instantiating a new Condition
InvalidItemException When a new product has invalid field values (id,name,price,quantity)
UnknownModelException When you try to associate a none existing model to a cart item.

Events

The cart has currently 9 events you can listen and hook some actons.

Event Fired
cart.created($cart) When a cart is instantiated
cart.adding($items, $cart) When an item is attempted to be added
cart.added($items, $cart) When an item is added on cart
cart.updating($items, $cart) When an item is being updated
cart.updated($items, $cart) When an item is updated
cart.removing($id, $cart) When an item is being remove
cart.removed($id, $cart) When an item is removed
cart.clearing($cart) When a cart is attempted to be cleared
cart.cleared($cart) When a cart is cleared

NOTE: For different cart instance, dealing events is simple. For example you have created another cart instance which you have given an instance name of "wishlist". The Events will be something like: {$instanceName}.created($cart)

So for you wishlist cart instance, events will look like this:

  • wishlist.created($cart)
  • wishlist.adding($items, $cart)
  • wishlist.added($items, $cart) and so on..

Format Response

Now you can format all the responses. You can publish the config file from the package or use env vars to set the configuration. The options you have are:

  • format_numbers or env('SHOPPING_FORMAT_VALUES', false) => Activate or deactivate this feature. Default to false,
  • decimals or env('SHOPPING_DECIMALS', 0) => Number of decimals you want to show. Defaults to 0.
  • dec_point or env('SHOPPING_DEC_POINT', '.') => Decimal point type. Defaults to a '.'.
  • thousands_sep or env('SHOPPING_THOUSANDS_SEP', ',') => Thousands separator for value. Defaults to ','.

Examples

// add items to cart
Cart::add(array(
  array(
      'id' => 456,
      'name' => 'Sample Item 1',
      'price' => 67.99,
      'quantity' => 4,
      'attributes' => array()
  ),
  array(
      'id' => 568,
      'name' => 'Sample Item 2',
      'price' => 69.25,
      'quantity' => 4,
      'attributes' => array(
        'size' => 'L',
        'color' => 'blue'
      )
  ),
));

// then you can:
$items = Cart::getContent();

foreach($items as $item)
{
    $item->id; // the Id of the item
    $item->name; // the name
    $item->price; // the single price without conditions applied
    $item->getPriceSum(); // the subtotal without conditions applied
    $item->getPriceWithConditions(); // the single price with conditions applied
    $item->getPriceSumWithConditions(); // the subtotal with conditions applied
    $item->quantity; // the quantity
    $item->attributes; // the attributes

    // Note that attribute returns ItemAttributeCollection object that extends the native laravel collection
    // so you can do things like below:

    if( $item->attributes->has('size') )
    {
        // item has attribute size
    }
    else
    {
        // item has no attribute size
    }
}

// or
$items->each(function($item)
{
    $item->id; // the Id of the item
    $item->name; // the name
    $item->price; // the single price without conditions applied
    $item->getPriceSum(); // the subtotal without conditions applied
    $item->getPriceWithConditions(); // the single price with conditions applied
    $item->getPriceSumWithConditions(); // the subtotal with conditions applied
    $item->quantity; // the quantity
    $item->attributes; // the attributes

    if( $item->attributes->has('size') )
    {
        // item has attribute size
    }
    else
    {
        // item has no attribute size
    }
});

Storage

Using different storage for the carts items is pretty straight forward. The storage class that is injected to the Cart's instance will only need methods.

Example we will need a wishlist, and we want to store its key value pair in database instead of the default session.

To do this, we will need first a database table that will hold our cart data. Let's create it by issuing php artisan make:migration create_cart_storage_table

Example Code:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCartStorageTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cart_storage', function (Blueprint $table) {
            $table->string('id')->index();
            $table->longText('cart_data');
            $table->timestamps();

            $table->primary('id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('cart_storage');
    }
}

Next, lets create an eloquent Model on this table so we can easily deal with the data. It is up to you where you want to store this model. For this example, lets just assume to store it in our App namespace.

Code:

namespace App;

use Illuminate\Database\Eloquent\Model;


class DatabaseStorageModel extends Model
{
    protected $table = 'cart_storage';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id', 'cart_data',
    ];

    public function setCartDataAttribute($value)
    {
        $this->attributes['cart_data'] = serialize($value);
    }

    public function getCartDataAttribute($value)
    {
        return unserialize($value);
    }
}

Next, Create a new class for your storage to be injected to our cart instance:

Eg.

class DBStorage {

    public function has($key)
    {
        return DatabaseStorageModel::find($key);
    }

    public function get($key)
    {
        if($this->has($key))
        {
            return new CartCollection(DatabaseStorageModel::find($key)->cart_data);
        }
        else
        {
            return [];
        }
    }

    public function put($key, $value)
    {
        if($row = DatabaseStorageModel::find($key))
        {
            // update
            $row->cart_data = $value;
            $row->save();
        }
        else
        {
            DatabaseStorageModel::create([
                'id' => $key,
                'cart_data' => $value
            ]);
        }
    }
}

For example you can also leverage Laravel's Caching (redis, memcached, file, dynamo, etc) using the example below. Example also includes cookie persistance, so that cart would be still available for 30 days. Sessions by default persists only 20 minutes.

namespace App\Cart;

use Carbon\Carbon;
use Cookie;
use Darryldecode\Cart\CartCollection;

class CacheStorage
{
    private $data = [];
    private $cart_id;

    public function __construct()
    {
        $this->cart_id = \Cookie::get('cart');
        if ($this->cart_id) {
            $this->data = \Cache::get('cart_' . $this->cart_id, []);
        } else {
            $this->cart_id = uniqid();
        }
    }

    public function has($key)
    {
        return isset($this->data[$key]);
    }

    public function get($key)
    {
        return new CartCollection($this->data[$key] ?? []);
    }

    public function put($key, $value)
    {
        $this->data[$key] = $value;
        \Cache::put('cart_' . $this->cart_id, $this->data, Carbon::now()->addDays(30));

        if (!Cookie::hasQueued('cart')) {
            Cookie::queue(
                Cookie::make('cart', $this->cart_id, 60 * 24 * 30)
            );
        }
    }
}

To make this the cart's default storage, let's update the cart's configuration file. First, let us publish first the cart config file for us to enable to override it. php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="config"

after running that command, there should be a new file on your config folder name shopping_cart.php

Open this file and let's update the storage use. Find the key which says 'storage' => null, And update it to your newly created DBStorage Class, which on our example, 'storage' => \App\DBStorage::class,

OR If you have multiple cart instance (example WishList), you can inject the custom database storage to your cart instance by injecting it to the service provider of your wishlist cart, you replace the storage to use your custom storage. See below:

use Darryldecode\Cart\Cart;
use Illuminate\Support\ServiceProvider;

class WishListProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('wishlist', function($app)
        {
            $storage = new DBStorage(); <-- Your new custom storage
            $events = $app['events'];
            $instanceName = 'cart_2';
            $session_key = '88uuiioo99888';
            return new Cart(
                $storage,
                $events,
                $instanceName,
                $session_key,
                config('shopping_cart')
            );
        });
    }
}

Still feeling confuse on how to do custom database storage? Or maybe doing multiple cart instances? See the demo repo to see the codes and how you can possibly do it and expand base on your needs or make it as a guide & reference. See links below:

See Demo App Here

OR

See Demo App Repo Here

License

The Laravel Shopping Cart is open-sourced software licensed under the MIT license

Disclaimer

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR, OR ANY OF THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

laravelshoppingcart's People

Contributors

aalyusuf avatar aaronflorey avatar abdelazizib avatar aidask avatar aimalamiri avatar alhaji-aki avatar asallay avatar beaudinn avatar belguinan avatar bryant1410 avatar csesumonpro avatar da-sie avatar darryldecode avatar davidavz avatar ebisbe avatar fabioferreira3 avatar frezno avatar it-can avatar junkystu avatar leonigas avatar lloricode avatar mateusjatenee avatar naxon avatar publiux avatar punyflash avatar pvdptje avatar saleem189 avatar sdunayer avatar simotod avatar turaylon 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  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

laravelshoppingcart's Issues

Time to live for cart.

Hello. How can I set time to live for goods in my cart.
In several hours cart becomes empty.

Order of the items in the cart

When I am updating the cart by adding or subtracting quantities (and loading the page with the cart again) the order of the items is changing. Is there a way to set the order? By example alphabetically on the items names? Or simply by the order the items are originally added to the cart?

Cart total or discount total display incorrect

cart conditions
Hi
I have configure cart and applied few condition for testing purpose but cart total or discount total is not display correctly can you please help me below is my code?

$condition1 = new \Darryldecode\Cart\CartCondition(array(
'name' => 'VAT',
'type' => 'tax',
'target' => 'subtotal',
'value' => '10%',
));

$itemCondition3 = new \Darryldecode\Cart\CartCondition(array(
'name' => 'Discount',
'type' => 'misc',
'target' => 'subtotal',
'value' => '-5%',
));

Cart::condition([$condition1,$itemCondition3]);

        <table class="table">
            <tbody>
                <tr>
                    <td>Order subtotal</td>
                    <th align="right">${{number_format(Cart::getSubTotal(),2)}}</th>
                </tr>
                @foreach(Cart::getConditions() as $condition)
                    <tr>
                        <td>{{$condition->getName()}} ({{$condition->getValue()}})</td>
                        <th align="right">${{number_format($condition->getCalculatedValue(Cart::getSubTotal()),2)}}</th>
                    </tr>                       
                @endforeach
                <tr class="total">
                    <td>Total</td>
                    <th align="right">${{number_format(Cart::getTotal(),2)}}</th>
                </tr>
            </tbody>
        </table>

Problem getTotal() method

Problem with getTotal method, if there are no conditions the total returns 0, I think convenient to put the condition: if $conditions->count() is false $newTotal = $subTotal

Add conditions to existing products in cart

Hi all,

I have a question about adding per-item conditions to already existing products in cart. I have a 'cart' page, which contains a form for coupons, which can be assigned to certain products/categories in the shop, so when the user is filling in his coupon, he might already have the product(s) on sale in the cart. Is there a way to assign a per-item condition to a certain existing product in cart.

Thank you.

Simple Instance

Possible to have instance like this?

Cart::instance('shopping')->add(455, 'Sample Item', 100.99, 2, array());

Possibility to have attributes on conditions.

What are you guys thinking of adding the possibility to have attributes on conditions. I have a condition with the name 'discount'. This because I only want to have the option to have one 'discount' rule so I can update the value if they enter another promo code. But I would like to add some more information on this condition due attributes.

->totalquantity() in addition of count()

Of course not so difficult to calculate myself but it would be nice to have a function to get the total quantity of all items in the cart. Now I have a quantity of 14 and stil just 1 when I use count().

Laravel 5.1

Will you be updating the cart for Laravel 5.1? I can't update to 5.1 until the cart will accept it.

Problem 1
- Installation request for darryldecode/cart dev-master -> satisfiable by darryldecode/cart[dev-master].
- Conclusion: remove laravel/framework v5.1.1
- Conclusion: don't install laravel/framework v5.1.1
- darryldecode/cart dev-master requires illuminate/validation 5.0.@dev -> satisfiable by illuminate/validation[v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.28, v5.0.4].
- don't install illuminate/validation v5.0.0|don't install laravel/framework v5.1.0
- don't install illuminate/validation v5.0.22|don't install laravel/framework v5.1.0
- don't install illuminate/validation v5.0.25|don't install laravel/framework v5.1.0
- don't install illuminate/validation v5.0.26|don't install laravel/framework v5.1.0
- don't install illuminate/validation v5.0.28|don't install laravel/framework v5.1.0
- don't install illuminate/validation v5.0.4|don't install laravel/framework v5.1.0
- Installation request for laravel/framework 5.1.
-> satisfiable by laravel/framework[v5.1.0, v5.1.1].

Cart session empty

Hi,

I'm having a problem.

In one route i add an item tot the cart with "Cart::add(455, 'Sample Item', 100.99, 2, array());" and in another route i get the items with "Cart::getContent()".

The problem is that Cart::getContent() always return empty.

I checked the session with Session::get() (and the session id) and the items appear but Cart::getContent always return an empty array.

Can you help me please?

Thanks.

Ability to find and remove conditions by type

I think it would be nice to be able to find and remove conditions by the type they are e.g.

$condition = new CartCondition([
    'name' => 'Discount 10%',
    'type' => 'promo',
    'target' => 'subtotal',
    'value' => '-10%',
]);


Cart::findCartConditionType('promo');
Cart::removeCartConditionType('promo');

5.2 support

Can you please add laravel 5.2 support? Now getting these errors:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for laravel/framework 5.2.* -> satisfiable by laravel/framework[v5.2.0].
    - darryldecode/cart dev-master requires illuminate/validation 5.0.x|5.1.x -> satisfiable by illuminate/validation[v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.28, v5.0.33, v5.0.4, v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.6, v5.1.8].
    - don't install illuminate/validation v5.0.0|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.0.22|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.0.25|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.0.26|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.0.28|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.0.33|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.0.4|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.1.1|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.1.13|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.1.16|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.1.2|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.1.20|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.1.22|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.1.25|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.1.6|don't install laravel/framework v5.2.0
    - don't install illuminate/validation v5.1.8|don't install laravel/framework v5.2.0
    - Installation request for darryldecode/cart dev-master -> satisfiable by darryldecode/cart[dev-master].

#46

Updating laravel to 5.3

Hi,
I'm using darryldecode/cart in my code, I'm using currently laravel 5.2, and i want to upgrade to 5.3.
when i run composer update, i get the following error:
Problem 1
- darryldecode/cart dev-master requires illuminate/validation 5.0.x|5.1.x|5.2.x -> satisfiable by laravel/framework[v5.2.39], illuminate/validation[v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.28, v5.0.33, v5.0.4, v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.28, v5.1.30, v5.1.31, v5.1.41, v5.1.6, v5.1.8, v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.6, v5.2.7].

Is the cart compatible with laravel 5.3 ?
Thanks!

Cart namespace

Hi , what namespace "use" at the top of controller for this cart module?

Thank you

The quantity is increasing on page refresh

Hi,

After I add a product and refresh the page, the quantity is increasing and is affecting the total price. It affects the quantity of only the last added product and not the ones before that.
Is this something that can be rectified?

Updating quantity issue

Hello,
first of all, thank you for the nice implementation.

I was quite surprised that the cart quantity update method actually adds quantity.
Is there a way to easy update the quantity with a certain value, e.g. if the quantity is 5 to make it 7 right away, and not 5+7=12?

Thanks

Type Hinting the Cart

I've tried to type hint the Cart so that I'm not doing static calls. From what I understand better for unit testing.

But the problem is that the _construct requires session, events and so on. Is there any way to do this?

I want to be able to do something like $this->cart-clear() or $this->cart->add()

Condition lives on after removing

When a new condition is added using the Cartcondition like below, the discount is calculated over the price, which is good.

$discountCondition = new \Darryldecode\Cart\CartCondition([
        'name' => 'discount-code',
        'type' => 'discount-code',
        'target' => 'subtotal',
        'value' => $discountValue, // (-30%)
        'attributes' => [
            'code' => $code
        ]
]);

\Cart::condition($discountCondition);

But when a customer removes the discount code, and I remove the condition (\Cart::removeCartCondition('discount-code');), the condition is removed after the code is executed, but when I reload the page, the condition is still applied. The condition is also shown in the \Cart::getConditions(); array.

Could you please take a look at it :)

getPriceSumWithConditions with specific types of conditions

I have an item in my cart with two conditions. One of them is shipping, the other one is Vat.

   $shippingCondition = new \Darryldecode\Cart\CartCondition(array(
      'name'       => 'shipping costs',
      'type'       => 'shipping',
      'target'     => 'item',
      'value'      => '3.95',
    ]
    ));
    $vatCondition      = new \Darryldecode\Cart\CartCondition(array(
       'name'       => 'vat 6%',
       'type'       => 'tax',
       'target'     => 'item',
       'value'      => '6%',
     ));

Items can be 6% or 21% vat in the Netherlands.

What I like to have is the possiblity to use specific conditions when showing the item in my cart:

   $item->getPriceSumWithConditions($vatCondition);

This way I can show the price with VAT per Item on a line in my cart and use the shipping at the end with the Cart totals summary.

And while mentioning this, it would be nice to have the possibility to sum up the totals per item condition too with a specific function. This way I can show the sum of the 6% en 21% Vat items separately, as well as the total shipping costs, which can vary per item.

Total Number of Items

This is probably a function you want to add. Most carts these days display the total number of items in the cart. I see no function for this. Not hard for me to write, but thought I'd mention it.

Clear all conditions

Hello.

It is possible to clean the all conditions?

Because the Cart::clear() only clean the cart. Even this option is not documented in the readme.

Thank you for your great work.

Item price lower than zero?

Hi,

I've noticed that if you add an item with a condition which ends up substracting more than the item's price, the item price ends up negative (e.g. price 15, value -20 results with -5 product price). Is that something that should be allowed? In my case, I would never want a negative product price. Please let me know and I can make a PR.

Test code:

$product = [
    'id' => 123,
    'name' => 'Sample Item 1',
    'price' => 15,
    'quantity' => 1,
    'conditions' => new \Darryldecode\Cart\CartCondition([
        'name' => 'Substract 20',
        'type' => 'shipping',
        'target' => 'item',
        'value' => '-20',
    ]),
];

\Cart::add($product);

dd(\Cart::getTotal()); // -5

Sum value of individual item (quantity * price).

One idea:

Would put a field with the sum total of each item (quantity * price).

Example:

Cart::get($itemId);

[id] => 23
[name] => Item Name
[price] => 5.00
[quantity] => 3
[sum] => 15.00

Thank you!

Cart does not return items in 5.2.*

I have installed package successfully ,

Cart::add(455, 'Sample Item', 100.99, 2, array());

Works , but get empty response when trying to retrieve the cart :

return Cart::getContent() ;

Unique item identifier

Have you considered to use something other then Item ID for Cart::update() and Cart::remove() functions? In cases where cart holds multiple instances of the same Item ID how do you work with items in the cart?

Database support.

Do you mind adding database support beside session only?
we've encountered several session problems because of ajax calls adding and removing from the cart.

we'd like to have a backup to the database without having to do it manually on each call.
(preferable to do both sides, sessions and db, or make it optional)

Great work on the project though, we've been using it for quiet a while now!

kind regards,
Jurien Hamaker.

Quantity as a decimal

I'm trying to adapt this very nice cart you've created on a project where the quantities are services based in time broken down by half hour. So a quantity could be 1.5 (1 and 1/2 hours). When I add 1.5 as a quantity it rounds down. I thought perhaps if I changed the validation but doing so didn't seem to have any effect.

Any tips on how I might make this adjustment?

Issue with add more than three items

Good day. I have a problem with the library and I would like to fix it because I am comfortable with its features, the problem is when I want to add more than 3 items to cart this not stored. Here I leave a link that leads to a picture of the implementation of the method add () http://prntscr.com/b6gqg2

Rename clearCartConditions() to clearConditions()

Because the class is already called "Cart", it's superfluous to have "cart" in method names.

// Instead of:
Cart::clearCartConditions();

// It should be:
Cart::clearConditions();

This is a consistency issue which bugs me personally. I keep forgetting to add Cart whenever I want to call that specific method. If you want to keep "cart" in the method name, at least make it consistent by changing Cart::clear() to Cart::clearCart().

But again, I recommend just renaming Cart::clearCartConditions() to Cart::clearConditions(). Cart::clearCartConditions() should be deprecated in the next version or just removed.

Cart::update()

Hi ,

Cart::update(456, array(
'quantity' => array(
'relative' => false,
'value' => 5
),
));

give me this :

ErrorException in Cart.php line 204:

preg_match() expects parameter 2 to be string, array given

[Laravel 5.2] Class 'Cart' not found

Hello,

Code in config/app.php

`'providers' => [

    Darryldecode\Cart\CartServiceProvider::class,        

],

'aliases' => [

    'Cart'      => Darryldecode\Cart\Facades\CartFacade::class,

],`

In Controller

tried Cart::add() got error Class 'Cart' not found

tried \Cart:add() got the same error

In header I used both

use Cart;

and use Darryldecode\Cart\Facades\CartFacade; with this I got another error:

Class 'App\Http\Controllers\Cart' not found

tried 'use Darryldecode\Cart\Cart;' as well. Same error

Cart::getTotal() in view

When I want to echo out the total value in the view, I get the following error:

ErrorException
Trying to get property of non-object.. {view file name}
/­vendor/­darryldecode/­cart/­src/­Darryldecode/­Cart/­Cart.php510
Line: $originalPrice = $item->price;

Of course I have some items in the cart, and all items have price set.

CartCollection {#401 ▼
  #items: array:2 [▼
    21 => array:6 [▼
      "quantity" => 6
      "id" => "21"
      "name" => "******************"
      "price" => 7800.0
      "attributes" => ItemAttributeCollection {#341 ▶}
      "conditions" => []
    ]
    31 => array:6 [▼
      "quantity" => 6
      "id" => "31"
      "name" => "**************"
      "price" => 1.0
      "attributes" => ItemAttributeCollection {#342 ▶}
      "conditions" => []
    ]
  ]
}

EDIT: its not always, when I clear the cart, no error happens. It's something with adding to the cart...

EDIT 2: some way one of my item differs from others:

CartCollection {#386 ▼
  #items: array:2 [▼
    21 => ItemCollection {#341 ▶}
    31 => array:6 [▶]
  ]
}

this is why error happens.. any idea?

EDIT 3:
When I constantly add, remove items to the cart, sometimes one of the items randomly will be saved as array, and not as ItemCollection. Of course I use the same code all the way..

CartCollection {#435 ▼
  #items: array:4 [▼
    21 => ItemCollection {#341 ▶}
    27 => ItemCollection {#343 ▶}
    22 => ItemCollection {#345 ▶}
    20 => array:6 [▶]
  ]
}

Conditions

Hi,
Its leave the whole conditions of the cart in session? Because I set a condition and on checkout I lose the getConditions() values.

Another thing, I tried something like $condition->getValue ()-> first () without the need to use a foreach. Is there any way?

Thank you.

How to use newly created cart instance?

Hi,

I needed to create a new cart instance and retain the same one throughout the session. So I created a new service provider and added the code in the register() method. Now how do I use this cart name/ instance while adding or updating my cart contents?

Thank You!

Weight, how can deal with this?

Hey,

First all, sorry about my english.
Make any sense if we can allow to put another argument on Cart::add for weight?

/**
     * add item to the cart, it can be an array or multi dimensional array
     *
     * @param string|array $id
     * @param string $name
     * @param float $price
     * @param int $quantity
     * @param array $attributes
     * @param CartCondition|array $conditions
     * @return $this
     * @throws InvalidItemException
     */
    public function add($id, $name = null, $price = null, $quantity = null, $attributes = array(), $conditions = array(), $weight = 0)
    {
        // if the first argument is an array,
        // we will need to call add again
        if( is_array($id) )
        {
            // the first argument is an array, now we will need to check if it is a multi dimensional
            // array, if so, we will iterate through each item and call add again
            if( Helpers::isMultiArray($id) )
            {
                foreach($id as $item)
                {
                    $this->add(
                        $item['id'],
                        $item['name'],
                        $item['price'],
                        $item['quantity'],
                        Helpers::issetAndHasValueOrAssignDefault($item['attributes'], array()),
                        Helpers::issetAndHasValueOrAssignDefault($item['conditions'], array()),
                        Helpers::issetAndHasValueOrAssignDefault($item['weight'], 0)
                    );
                }
            }
            else
            {

                $this->add(
                    $id['id'],
                    $id['name'],
                    $id['price'],
                    $id['quantity'],
                    Helpers::issetAndHasValueOrAssignDefault($id['attributes'], array()),
                    Helpers::issetAndHasValueOrAssignDefault($id['conditions'], array()),
                    Helpers::issetAndHasValueOrAssignDefault($item['weight'], 0)
                );
            }

            return $this;
        }

        // validate data
        $item = $this->validate(array(
            'id' => $id,
            'name' => $name,
            'price' => Helpers::normalizePrice($price),
            'quantity' => $quantity,
            'attributes' => new ItemAttributeCollection($attributes),
            'conditions' => $conditions,
            'weight' => $weight
        ));

        // get the cart
        $cart = $this->getContent();

        // if the item is already in the cart we will just update it
        if( $cart->has($id) )
        {
            $this->events->fire($this->getInstanceName().'.updating', array($item, $this));

            $this->update($id, $item);

            $this->events->fire($this->getInstanceName().'.updated', array($item, $this));
        }
        else
        {
            $this->events->fire($this->getInstanceName().'.adding', array($item, $this));

            $this->addRow($id, $item);

            $this->events->fire($this->getInstanceName().'.added', array($item, $this));
        }

        return $this;
    }

Next we can add"tax" by weight? Or get total weight? Or even calculating shipping cost?

What you think about this?

How add one item twice with different attributes ?

Hello,
I would like add the same item, but with different attributes.
e.g.:
item in cart has attribute = ['color' => 'red'],
and I would like to add the same item with attribute = ['color' => 'blue'].

I except two items with different arguments in cart, but old item`s attributes are overwritten with new attributes and quantity is updated to 2.
I didn't find this in documentation, maybe I missed it.
Is there any way how to achieve this, please ?

...Thank You.

Ability to fetch the Monetary Value from Cart Condition

Could you add the ability to fetch the actual value from the condition rather than what you supply it:

for example:

Name Value
cart sub total £10
vat @ 20% £2
total £12

Currently when you do $condition->getValue() it only returns the value you supplied in the condition.

// add condition single condition
$condition = new CartCondition([
    'name'      => 'VAT 20%',
    'type'      => 'tax',
    'target'    => 'total',
    'value'     => '20%',
]);

What we really need is another method like $condition->getCalculateValue() will return the value that targets the sub total, or whatever value you have applied the condition to.

How to access parsedRawValue?

In a condition I have the calculated value from that condition.

object(Darryldecode\Cart\CartCondition)[293]
  private 'args' => 
    array (size=5)
      'name' => string 'Coupon' (length=22)
      'type' => string 'discount' (length=8)
      'target' => string 'subtotal' (length=8)
      'value' => string '-10%' (length=4)
      'attributes' => 
        array (size=3)
          'title' => string 'Lorem ipsum dolor' (length=15)
          'description' => string '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Dempta enim aeternitate nihilo beatior Iuppiter quam Epicurus; Ubi ut eam caperet aut quando? Hoc est non dividere, sed frangere. Duo Reges: constructio interrete. Eiuro, inquit adridens, iniquum, hac quidem de re;</p>

' (length=348)
          'valid until' => string '2016-06-15' (length=10)
  private 'parsedRawValue' => float 1.045

How can I use it?

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.