5 ways to implement shopping cart in laravel

1- shoppingcart
Laravel 5
"require": {
"laravel/framework": "5.0.*",
"gloudemans/shoppingcart": "~1.3"
}
Next, run the Composer update command from the Terminal:
composer Now all you have to do is add the service provider of the package and alias the package. To do this open your app/config/app.php file.
Add a new line to the service providers array:
'Gloudemans\Shoppingcart\ShoppingcartServiceProvider'
And finally add a new line to the aliases array:
'Cart' => 'Gloudemans\Shoppingcart\Facades\Cart',
Now you’re ready to start using the shoppingcart in your application.
Usage
The shoppingcart gives you the following methods to use:
Cart::add()
/**
* Add a row to the cart
*
* @param string|Array $id Unique ID of the item|Item formated as array|Array of items
* @param string $name Name of the item
* @param int $qty Item qty to add to the cart
* @param float $price Price of one item
* @param Array $options Array of additional options, such as 'size' or 'color'
*/
// Basic form
Cart::add('293ad', 'Product 1', 1, 9.99, array('size' => 'large'));
// Array form
Cart::add(array('id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'options' => array('size' => 'large')));
// Batch method
Cart::add(array(
array('id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 10.00),
array('id' => '4832k', 'name' => 'Product 2', 'qty' => 1, 'price' => 10.00, 'options' => array('size' => 'large'))
));
Cart::update()
/**
* Update the quantity of one row of the cart
*
* @param string $rowId The rowid of the item you want to update
* @param integer|Array $attribute New quantity of the item|Array of attributes to update
* @return boolean
*/
$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';
Cart::update($rowId, 2);
OR
Cart::update($rowId, array('name' => 'Product 1'));
Cart::remove()
/**
* Remove a row from the cart
*
* @param string $rowId The rowid of the item
* @return boolean
*/
$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';
Cart::remove($rowId);
Cart::get()
/**
* Get a row of the cart by its ID
*
* @param string $rowId The ID of the row to fetch
* @return CartRowCollection
*/
$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';
Cart::get($rowId);
Cart::content()
/**
* Get the cart content
*
* @return CartCollection
*/
Cart::content();
Cart::destroy()
/**
* Empty the cart
*
* @return boolean
*/
Cart::destroy();
Cart::total()
/**
* Get the price total
*
* @return float
*/
Cart::total();
Cart::count()
/**
* Get the number of items in the cart
*
* @param boolean $totalItems Get all the items (when false, will return the number of rows)
* @return int
*/
Cart::count(); // Total items
Cart::count(false); // Total rows
Cart::search()
/**
* Search if the cart has a item
*
* @param Array $search An array with the item ID and optional options
* @return Array|boolean
*/
Cart::search(array('id' => 1, 'options' => array('size' => 'L'))); // Returns an array of rowid(s) of found item(s) or false on failure
Collections
As you might have seen, the Cart::content() and Cart::get() methods both return a Collection, a CartCollection and a CartRowCollection.
These Collections extends the ‘native’ Laravel 4 Collection class, so all methods you know from this class can also be used on your shopping cart. With some addition to easily work with your carts content.
Instances
Now the packages also supports multiple instances of the cart. The way this works is like this:
You can set the current instance of the cart with Cart::instance('newInstance'), at that moment, the active instance of the cart is newInstance, so when you add, remove or get the content of the cart, you work with the newInstance instance of the cart. If you want to switch instances, you just call Cart::instance('otherInstance') again, and you’re working with the otherInstance again.
So a little example:
Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99);
// Get the content of the 'shopping' cart
Cart::content();
Cart::instance('wishlist')->add('sdjk922', 'Product 2', 1, 19.95, array('size' => 'medium'));
// Get the content of the 'wishlist' cart
Cart::content();
// If you want to get the content of the 'shopping' cart again...
Cart::instance('shopping')->content();
// And the count of the 'wishlist' cart again
Cart::instance('wishlist')->count();
N.B. Keep in mind that the cart stays in the last set instance for as long as you don’t set a different one during script execution.
N.B.2 The default cart instance is called main, so when you’re not using instances,Cart::content(); is the same as Cart::instance('main')->content().
Models
A new feature is associating a model with the items in the cart. Let’s say you have a Product model in your application. With the new 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 right from the CartRowCollection!
Here is an example:
<?php
/**
* Let say we have a Product model that has a name and description.
*/
Cart::associate('Product')->add('293ad', 'Product 1', 1, 9.99, array('size' => 'large'));
$content = Cart::content();
foreach($content as $row)
{
echo 'You have ' . $row->qty . ' items of ' . $row->product->name . ' with description: "' . $row->product->description . '" in your cart.';
}
The key to access the model is the same as the model name you associated (lowercase). The associate() method has a second optional parameter for specifying the model namespace.
Exceptions
The Cart package will throw exceptions if something goes wrong. This way it’s easier to debug your code using the Cart package or to handle the error based on the type of exceptions. The Cart packages can throw the following exceptions:
| Exception | Reason |
|---|---|
| ShoppingcartInstanceException | When no instance is passed to the instance() method |
| ShoppingcartInvalidItemException | When a new product misses one of it’s arguments (id, name, qty, price) |
| ShoppingcartInvalidPriceException | When a non-numeric price is passed |
| ShoppingcartInvalidQtyException | When a non-numeric quantity is passed |
| ShoppingcartInvalidRowIDException | When the $rowId that got passed doesn’t exists in the current cart |
| ShoppingcartUnknownModelException | When an unknown model is associated to a cart row |
Events
The cart also has events build in. There are five events available for you to listen for.
| Event | Fired |
|---|---|
| cart.add($item) | When a single item is added |
| cart.batch($items) | When a batch of items is added |
| cart.update($rowId) | When an item in the cart is updated |
| cart.remove($rowId) | When an item is removed from the cart |
| cart.destroy() | When the cart is destroyed |
Example
Below is a little example of how to list the cart content in a table:
// Controller
Cart::add('192ao12', 'Product 1', 1, 9.99);
Cart::add('1239ad0', 'Product 2', 2, 5.95, array('size' => 'large'));
// View
<table>
<thead>
<tr>
<th>Product</th>
<th>Qty</th>
<th>Item Price</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody>
<?php foreach($cart as $row) :?>
<tr>
<td>
<p><strong><?php echo $row->name;?></strong></p>
<p><?php echo ($row->options->has('size') ? $row->options->size : '');?></p>
</td>
<td><input type="text" value="<?php echo $row->qty;?>"></td>
<td>$<?php echo $row->price;?></td>
<td>$<?php echo $row->subtotal;?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
2 – Laravel Shopping Basket Package
Laravel Facade and Service Provider for Lenius\Basket
Installation
To use, simply install the package via Composer and then add the following to your app/config/app.php to the service providers array:
'Lenius\Basket\BasketServiceProvider',
You should then be good to go and be able to access the basket using the following static interface:
//Format array of required info for item to be added to basket...
$items = array(
'id' => 1,
'name' => 'Dog',
'price' => 120.00,
'quantity' => 1,
'weight' => 200
);
//Make the insert...
Basket::insert($items);
//Let's see what we have got in their...
dd(Basket::totalItems());
Setting the tax rate for an item
Another key you can pass to your insert method is ‘tax’. This is a percentage which you would like to be added onto the price of the item.
In the below example we will use 25% for the tax rate.
Basket::insert(array(
'id' => 'mouseid',
'name' => 'Mouse',
'price' => 100,
'quantity' => 1,
'tax' => 25,
'weight' => 200
));
Updating items in the Basket
You can update items in your Basket by updating any property on a Basket item. For example, if you were within a Basket loop then you can update a specific item using the below example.
foreach (Basket::contents() as $item) {
$item->name = 'Foo';
$item->quantity = 1;
}
Removing Basket items
You can remove any items in your Basket by using the remove() method on any Basket item.
foreach (Basket::contents() as $item) {
$item->remove();
}
Destroying/emptying the Basket
You can completely empty/destroy the Basket by using the destroy() method.
Basket::destroy()
Retrieve the Basket contents
You can loop the Basket contents by using the following method
Basket::contents();
You can also return the Basket items as an array by passing true as the first argument
Basket::contents(true);
Retrieving the total items in the Basket
Basket::totalItems();
By default this method will return all items in the Basket as well as their quantities. You can pass true as the first argument to get all unique items.
Basket::totalItems(true);
Retrieving the Basket total
$Basket->total();
By default the total() method will return the total value of the Basket as a float, this will include any item taxes. If you want to retrieve the Basket total without tax then you can do so by passing false to the total() method
Basket::total(false);
Check if the Basket has an item
Basket::has($itemIdentifier);
Retreive an item object by identifier
Basket::item($itemIdentifier);
Basket items
There are several features of the Basket items that may also help when integrating your Basket.
Retrieving the total value of an item
You can retrieve the total value of a specific Basket item (including quantities) using the following method.
Basket::total();
By default, this method will return the total value of the item plus tax. So if you had a product which costs 100, with a quantity of 2 and a tax rate of 20% then the total returned by this method would be 240.
You can also get the total minus tax by passing false to the total() method.
Basket::total(false);
This would return 200.
Check if an item has options
You can check if a Basket item has options by using the hasOptions() method.
if ($item->hasOptions()) {
// We have options
}
Remove an item from the Basket
$item->remove();
You can also get the total weight for a single item
$item->weight();
Output the item data as an array
$item->toArray();
3 – Laravel Shopping Cart Package
aravel Facade and Service Provider for Moltin\Cart
Installation
To use, simply install the package via Composer and then add the following to your app/config/app.php to the service providers array:
'Moltin\Cart\CartServiceProvider',
Then add to the aliases array the following:
'Cart' => 'Moltin\Cart\Facade',
You should then be good to go and be able to access the cart using the following static interface:
// Format array of required info for item to be added to basket...
$items = array(
'id' => 1,
'name' => 'Juicy Picnic Hamper',
'price' => 120.00,
'quantity' => 1
);
// Make the insert...
Cart::insert($items);
// Let's see what we have have in there...
dd(Cart::totalItems());
Config settings (Optional)
Publish the config file with php artisan vendor:publish
return array(
'storage' => 'session', //session, cache
// Cache
// Laravel documentation for more information
'cache_prefix' => 'moltin_cart_',
'cache_expire' => '-1', //in minutes, -1 permanent caching
// Identifier
// With a requestcookie (choose for storage: cache, the session will be expired), the cart could be reloaded from a http request, example: the customer could save his cart link (email, hyperlink) and reopen this later.
// If there is no request, the cookie will be loaded.
'identifier' => 'cookie', //cookie, requestcookie
//Request Cookie
'requestid' => 'CartID', //http input request identifier, example: your customer/backoffice could reload the cart in your shop controller, /public/shop?CartID=871f0bc18ca76e68bf7c3adf8f9426ef
);
Setting the tax rate for an item
Another key you can pass to your insert method is ‘tax’. This is a percentage which you would like to be added onto the price of the item.
In the below example we will use 20% for the tax rate.
Cart::insert(array(
'id' => 'foo',
'name' => 'bar',
'price' => 100,
'quantity' => 1,
'tax' => 20
));
Updating items in the cart
You can update items in your cart by updating any property on a cart item. For example, if you were within a cart loop then you can update a specific item using the below example.
foreach (Cart::contents() as $item) {
$item->name = 'Foo';
$item->quantity = 1;
}
Removing cart items
You can remove any items in your cart by using the remove() method on any cart item.
foreach (Cart::contents() as $item) {
$item->remove();
}
Destroying/emptying the cart
You can completely empty/destroy the cart by using the destroy() method.
Cart::destroy()
Retrieve the cart contents
You can loop the cart contents by using the following method
Cart::contents();
You can also return the cart items as an array by passing true as the first argument
Cart::contents(true);
Retrieving the total items in the cart
Cart::totalItems();
By default this method will return all items in the cart as well as their quantities. You can pass true as the first argument to get all unique items.
Cart::totalItems(true);
Retrieving the cart total
$cart->total();
By default the total() method will return the total value of the cart as a float, this will include any item taxes. If you want to retrieve the cart total without tax then you can do so by passing false to the total() method
Cart::total(false);
Check if the cart has an item
Cart::has($itemIdentifier);
Retreive an item object by identifier
Cart::item($itemIdentifier);
Cart items
There are several features of the cart items that may also help when integrating your cart.
Retrieving the total value of an item
You can retrieve the total value of a specific cart item (including quantities) using the following method.
$item->total();
By default, this method will return the total value of the item plus tax. So if you had a product which costs 100, with a quantity of 2 and a tax rate of 20% then the total returned by this method would be 240.
You can also get the total minus tax by passing false to the total() method.
$item->total(false);
This would return 200.
Check if an item has options
You can check if a cart item has options by using the hasOptions() method.
if ($item->hasOptions()) {
// We have options
}
Remove an item from the cart
$item->remove();
Output the item data as an array
$item->toArray();
4 – Pedlar-Cart Laravel Package
Installation
Add bobkingstone/pedlar-cart to your composer.json
"require": {
"bobkingstone/pedlar-cart": "dev-master"
}
Run composer update
composer Once this has completed add the service provider to the array of providers in app/config/app.php
'Bobkingstone\PedlarCart\PedlarCartServiceProvider'
Usage
The package generates a ‘Cart’ facade for the package automatically so there is no need to add it to the alias array.
To add an item to the cart:
$item = array(
'id => '1', //your cart id
'qty' => 2,
'price' => 200.00,
);
$CartItemIdentifier = Cart::insert($item);
To get the total number of all items in cart:
Cart::countItems();
To get an array of CartItems from cart:
Cart::all();
To access cart items values:
foreach (Cart::all() as $item)
{
echo $item->id;
echo $item->price;
echo $item->qty;
};
To get the total value of all items in cart:
Cart::totalValue();
To get a count of unique items in cart:
Cart::totalUniqueItems();
To empty the cart:
Cart::clear();
To set tax rate, you can either add it to each item:
$item = array(
'id => '1',
'qty' => 2,
'tax' => 20,
'price' => 200.00,
);
Cart::totalWithTax();
Or pass in the percentage with the cart total calculation (this will override each items predefined tax rate):
Cart::totalWithTax(20);
To update an item
$item = Cart::find('91936a0df88d531b5a770b614cd3c1ea');
$item->update('qty','3');
This will replace the existing value, to add to the quantity add the same item:
$item = array(
'id => '1',
'qty' => 2,
'price' => 200.00,
);
Cart::insert($item);
The item quantity will automatically be added.
To remove a single item from cart:
Cart::remove(
Exceptions
The package will throw InvalidNumberOfValuesException if one of the following required params is missing:
$requiredParams = array (
'id',
'qty',
'price'
);
It will also throw InvalidItemKeyException if an invalid update is passed to a cart item.
Notes
Using dd() to view cart contents will interrupt Laravels Session storage functions and can prevent the cart from being updated.
5 – LaraCart – Laravel 5.1 Shopping Cart Package
!!WARNING!! Currently In Development
There are features that are incomplete and others that are not fully tested, please feel free to submit issues and enhancements
Features
- Display Currency along with Locale
- Easy Session Base Usage
- Totals / SubTotals with taxes
- Items have locale and currency and tax separate from the cart
- Multiple Cart Instances
- Unique Item Hash that is updated after every update to the item
- Option can have prices and are calculated in the totals and sub totals
Installation
Install the package through Composer. Edit your project’s composer.json file by adding:
composer Include Service Providers / Facade in app/config/app.php:
LukePOLO\LaraCart\LaraCartServiceProvider::class,
Optionally include the Facade (suggested) :
'LaraCart' => LukePOLO\LaraCart\Facades\LaraCart::class,
Copy over the configuration file by running the command :
Look through the configuration options and change as needed
Usage
Note : Because of the item hashing you must be careful how you update your items.Each change to an item will update its hash either continue to use the same item object or make sure to use the hash that is returned.
Adding an Item to the cart
// First way we can just add like this
LaraCart::add(1, 'Burger', 5, 2.00, [
// Notice this is an array of arrays,
// this allows us to further expand the cart functions to the options
[
'Description' => 'Bacon',
'Price' => 1.00
]
]);
// You can also do simple arrays for convenience
LaraCart::add(2, 'Shirt', 200, 15.99, [
'Size' => 'XL'
]);
// If you need line items rather than just updating the qty you can do
LaraCart::addLine(2, 'Shirt', 200, 15.99, [
'Size' => 'XL'
]);
Cart Attributes
// Sometimes you want to give a cart some kind of attributes , such as labels
LaraCart::addAttribute('label', 'Luke's Cart');
LaraCart::updateAttribute('label', 'Not Luke's Cart');
LaraCart::removeAttribute('label');
// Gets all the attributes
LaraCart::getAttributes();
Updating an Items Attributes
LaraCart::updateItem($itemHash, 'name', 'CheeseBurger w/Bacon');
LaraCart::updateItem($itemHash, 'qty', 5);
LaraCart::updateItem($itemHash, 'price', '2.50');
Removing an item
LaraCart::removeItem($itemHash);
Empty / Destroying the Cart
// Empty will only empty the contents
LaraCart::emptyCart()
// Destroy will remove the entire instance of the cart including coupons ect.
LaraCart::destroyCart()
Get the contents of the cart
LaraCart::getItems();
Find a specific item in the cart
LaraCart::findItem($itemHash);
Gets the total number of items in the cart
LaraCart::count();
Display Item Price with Locale
// $tax = false by default
$cartItem->getPrice($tax); // $24.23 | USD 24.23
Get the subtotal of the item
// $tax = false by default
$cartItem->subTotal($tax);
// Gets the totals for the item options if applicable
$cartItem->optionsTotal($formatMoney = true);
Add Option to Item
$cartItem->addOption([
'Description' => 'Fries',
'Price' => '.75'
]);
Updating Options
// Replacing an options value
// $cartItem->id = '123';
// This updates the "Description" to "No Cheese"
$cartItem->updateOption('123', 'Description', 'No Cheese', $updateByKey = 'id');
// Replace all options with the new options
$cartItem->updateOptions([
[
'Description' => 'Extra Cheese',
'Price' => '.25'
]
]);
// You can either use the built in option 'id'
$cartItem->removeOption($optionID, $removeByKey = 'id');
// Or you can use your own
$cartItem->removeOption($optionName, $removeByKey = 'optionName');
Get the Sub-Total of the cart (This also includes the prices in the options array!)
// By default $tax = false
LaraCart::subTotal($tax);
Get the total of the cart
// By default $tax = true
LaraCart::total($tax);
Instances
Instances is a way that we can use multiple carts within the same session. By using:
LaraCart::setInstance('yourInstanceName');
Will switch to that instance of the cart. Each following request reuse the last instance of the cart set
Exceptions
LaraCart packages can throw the following exceptions:
| Exception | Reason |
|---|---|
| InvalidOption | When trying to update an option on an item, cannot find a key value pair that matches |
| InvalidPrice | When trying to give an item a non currency format |
| InvalidQuantity | When trying to give an item a non-integer for a quantity |
| UnknownItemProperty | When trying to update an items attribute that doesn’t exists |
Events
The cart also has events build in:
| Event | Fired |
|---|---|
| laracart.new | When a new cart is started |
| laracart.update | When a the cart is updated to the session |
| laracart.addItem($cartItem) | When a item is added to the cart |
| laracart.updateItem($cartItem) | When a item is updated |
| laracart.updateHash($cartItem) | When a item hash is updated |
| laracart.removeItem($itemHash) | When a item is removed from the cart |
| laracart.empty($cartInstance) | When a cart is emptied |
| laracart.destroy($cartInstance) | When a cart is destroyed |