Preface
Introduction
A modern and framework agnostic shopping cart package featuring multiple instances, item attributes and Conditions.
The package requires PHP 8.2+ and comes bundled with a Laravel 11 Facade and a Service Provider to simplify the optional framework integration and follows the FIG standard PSR-4 to ensure a high level of interoperability between shared PHP code and is fully unit-tested.
Have a read through the Installation Guide and on how to Integrate it with Laravel 11.
Features
- Versatile Easily add, remove, update multiple or single items to a cart instance.
- Instances Supports multiple carts so you can have wish lists, saved carts, etc.
- Conditions Powerful condition systems allows you to fully manipulate a cart instance.
- Events Thorough events fired throughout the system that can be listened for.
- Search Quickly find items within cart instances using one or multiple properties.
- Metadata Manage metadata inside a cart instance such as billing, shipping, & anything.
- synchronization Synchronize cart collections from external sources.
- Attributes Manipulate items using attributes like size, color. Optionally adjust price, weight.
- Smart Methods Return totals, subtotals, quantities, weights.
Examples
Add a single item to the cart
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
]);
Add multiple items to the cart
Cart::add([
[
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
],
[
'id' => 'sweatshirt',
'name' => 'Sweatshirt',
'quantity' => 1,
'price' => 98.32,
],
]);
Get all the cart items
$items = Cart::items();
Setup
Installation
The best and easiest way to install the Cart package is with Composer.
Preparation
Open your composer.json
file and add the following to the require
array:
"cartalyst/cart": "^8.0"
Note: This version is still under development.
Add the following lines after the require
array on your composer.json
file:
"repositories": [
{
"type": "composer",
"url": "https://packages.cartalyst.com"
}
]
Note: Make sure that after the required changes your
composer.json
file is valid by runningcomposer validate
.
Install the dependencies
Run Composer to install or update the new requirement.
php composer install
or
php composer update
Now you are able to require the vendor/autoload.php
file to autoload the package.
Integration
Cartalyst packages are framework agnostic and as such can be integrated easily natively or with your favorite framework.
Laravel
The Cart package has optional support for Laravel 11 and it comes bundled with a Service Provider and a Facade for easy integration.
After installing the package, open your Laravel config file located at config/app.php
and add the following lines.
In the $providers
array add the following service provider for this package.
'Cartalyst\Cart\Laravel\CartServiceProvider',
In the $aliases
array add the following facade for this package.
'Cart' => 'Cartalyst\Cart\Laravel\Facades\Cart',
Configuration
After installing, you can publish the package configuration file into your application by running the following command on your terminal:
php artisan vendor:publish
This will publish the config file to config/cartalyst.cart.php
where you can modify the package configuration.
Native
Integrating the package outside of a framework is incredible easy, just follow the example below.
// Include the composer autoload file
require_once 'vendor/autoload.php';
// Import the necessary classes
use Cartalyst\Cart\Cart;
use Cartalyst\Cart\Storage\NativeSession;
use Illuminate\Events\Dispatcher;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Session\FileSessionHandler;
use Illuminate\Session\Store;
// Require the cart config file
$config = require_once 'vendor/cartalyst/cart/src/config/config.php';
// Instantiate a new Session storage
$fileSessionHandler = new FileSessionHandler(new Filesystem(), __DIR__.'/storage/sessions');
$store = new Store('your_app_session_name', $fileSessionHandler);
$session = new NativeSession($store, $config['instance'], $config['session_key']);
// Instantiate the Cart and set the necessary configuration
$cart = new Cart($session, new Dispatcher);
$cart->setRequiredIndexes($config['requiredIndexes']);
The integration is done and you can now use all the available methods, here's an example:
// Get all the items from the cart
$items = $cart->items();
Note 1: Please make sure that the
storage/sessions
folder exists and has write access by the web server. This can be changed to another folder if required.Note 2: To setup garbage collection, call the
gc()
method on the FileSessionHandler$fileSessionHandler->gc($lifetime);
, You can also setup a function that randomizes calls to this function rather than calling it on every request.
Usage
In this section we'll show how you can manage your shopping cart.
Add Item
Having the ability to add items to the shopping cart is crucial and we've made it incredible simple to do it.
You can pass a simple or a multidimensional array and to help you get started, we have listed below all the default indexes
that you can pass when adding or updating a cart item.
Indexes
Key | Required | Type | Description |
---|---|---|---|
id | true | mixed | The item unique identifier, can be a numeric id, an sku, etc.. |
name | true | string | The item name. |
price | true | float | The item price. |
quantity | true | int | The quantity, needs to be an integer and can't be a negative value. |
attributes | false | array | The item attributes like size, color, fabric, etc.. |
weight | false | float | The item weight. |
Note: You can pass custom
key
/value
pairs into the array when adding or updating an item, please check the examples below.
Cart::add()
Param | Required | Type | Description |
---|---|---|---|
$item | true | array | A single or multidimensional array that respects the list of indexes above. |
Add a single item
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
]);
Add a single item with a custom index
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
'sku' => 'tshirt-custom',
]);
Add a single item with attributes
and a custom index
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
'sku' => 'tshirt-red-large',
'attributes' => [
'color' => [
'label' => 'Red',
'value' => 'red',
],
'size' => [
'label' => 'Large',
'value' => 'l',
],
],
]);
Adding multiple items
Cart::add([
[
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
'sku' => 'tshirt-red-large',
'attributes' => [
'color' => [
'label' => 'Red',
'value' => 'red',
],
'size' => [
'label' => 'Large',
'value' => 'l',
],
],
],
[
'id' => 'sweatshirt',
'name' => 'Sweatshirt',
'quantity' => 1,
'price' => 98.32,
],
]);
Update Item
Updating items is as simple as adding them.
Cart::update()
Param | Required | Type | Description |
---|---|---|---|
$rowId | true | string | The item row id. |
$data | true | mixed | This can be either an array or an integer, if an integer, it'll update the item quantity. |
Note: If the
$data
is an array, it doesn't require you to pass all theindexes
, just the ones you wish to update, likename
,price
,quantity
,attributes
, etc..
Update an item quantity
Cart::update('c14c437bc9ae7d35a7c18ee151c6acc0', ['quantity' => 2]);
Update a single item
Cart::update('c14c437bc9ae7d35a7c18ee151c6acc0', [
'quantity' => 1,
'price' => 12.50,
]);
Update multiple items
Cart::update([
'c14c437bc9ae7d35a7c18ee151c6acc0' => [
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
],
'63e2d7033fe95b9134a5737503d10ba5' => [
'id' => 'sweatshirt',
'name' => 'Sweatshirt',
'quantity' => 2,
'price' => 98.32,
],
]);
Remove Item
Removing items from the cart is easy, you can remove one item at a time or multiple by providing an array containing the row ids that you wish to remove.
Cart::remove()
Param | Required | Type | Description |
---|---|---|---|
$items | true | mixed | This can be either a string or an array containing item row ids. |
Remove a single item
Cart::remove('c14c437bc9ae7d35a7c18ee151c6acc0');
Remove multiple items
Cart::remove([
'c14c437bc9ae7d35a7c18ee151c6acc0',
'63e2d7033fe95b9134a5737503d10ba5',
]);
Items
Need to show the items that are inside your shopping cart? We've you covered!
You can list all the items or grab individual items using their row ids.
Get all the items
$items = Cart::items();
foreach ($items as $item)
{
echo $item->price();
}
Check if an item exists
This method is most useful when deleting cart items, you can check if the item still exists on the cart before deleting it.
if (Cart::exists('c14c437bc9ae7d35a7c18ee151c6acc0'))
{
Cart::remove('c14c437bc9ae7d35a7c18ee151c6acc0');
}
Get a single item
$item = Cart::item('c14c437bc9ae7d35a7c18ee151c6acc0');
Get the item price
$item->price();
Get the item price + the item attributes total price
$item->price(true);
Get the item quantity
$item->quantity();
Get the item subtotal
$item->subtotal();
Get the item weight
$item->weight();
Get the item attributes
$item->attributes();
Other Methods
In this section we're covering all the other methods that didn't fit in on the previous sections.
Cart::total()
Returns the cart total.
echo Cart::total();
Cart::subtotal()
Returns the cart subtotal.
echo Cart::subtotal();
Cart::quantity()
Returns the total number of items that are in the cart.
echo Cart::quantity();
Cart::weight()
Returns the total cart weight.
echo Cart::weight();
Cart::itemsSubtotal()
Get the subtotal of the items in the Cart
echo Cart::itemsSubtotal();
Cart::clear()
Empty the Cart
Cart::clear();
Cart::getIdentity()
Returns the cart identifier.
Cart::getIdentity();
Cart::setIdentity()
Sets the cart identifier.
Cart::setIdentity('my-new-cart-name');
Cart::sync()
This method is very useful when you want to synchronize a shopping cart that is stored on the database for example.
In this quick example, we're using a static array.
$items = [
[
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
],
[
'id' => 'sweatshirt',
'name' => 'Sweatshirt',
'quantity' => 1,
'price' => 98.32,
],
];
$collection = new Collection($items);
Cart::sync($collection);
Metadata
Managing metadata inside the cart like shipping or billing information is very easy.
Cart::setMetaData()
Setting metadata is very easy, just provide an array with a key
/value
pair and you're done.
Param | Required | Type | Description |
---|---|---|---|
$key | true | string | The metadata key. |
$data | true | array | Array containing the data you want to attach. |
$data = [
'full_name' => 'John Doe',
'address' => 'Example Street',
];
Cart::setMetaData('shipping_information', $data);
Cart::setMetaData('shipping_information.street', 'Street ABC');
Cart::getMetaData()
Returning the metadata that you've set is simple.
Param | Required | Type | Description |
---|---|---|---|
$key | false | mixed | The metadata key to return. |
To return all the available metadata
$metadata = Cart::getMetaData();
To return metadata by keys
$metadata = Cart::getMetaData('shipping_information');
$metadata = Cart::getMetaData('shipping_information.full_name');
Cart::removeMetaData()
Param | Required | Type | Description |
---|---|---|---|
$key | false | mixed | The metadata key to remove. |
To remove all the metadata
Cart::removeMetaData();
To remove metadata by keys
Cart::removeMetaData('shipping_information.full_name');
Cart::removeMetaData('shipping_information');
Search
You can use one or multiple properties to search for items in the cart.
Cart::find()
Param | Required | Type | Description |
---|---|---|---|
$data | true | array | Array of properties you want to search. |
Example 1
Search for an item that has the id foobar
Cart::find([
'id' => 'foobar',
]);
Example 2
Search for an item thas has the name Foo Bar
and the price 5
Cart::find([
'name' => 'Foo Bar',
'price' => 5,
]);
Example 3
Search for items with the following attributes
Cart::find([
'attributes' => [
'size' => [
'price' => 5,
],
],
]);
Attributes
Each item can have different attributes like size, color and you can even add a price to each attribute that will reflect on the final item price.
Key | Required | Description |
---|---|---|
label | true | The name that is displayed to the end user. |
value | true | The attribute value. |
price | false | The attribute price. |
weight | false | The attribute weight. |
Note: You can pass custom
key
/value
pairs into the array, please check the examples below.
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
'attributes' => [
'size' => [
'label' => 'Large',
'value' => 'l',
'price' => 5,
],
'color' => [
'label' => 'Red',
'value' => 'red',
],
],
]);
Collections
Collections are merely a wrapper for an array of objects, but offers a bunch of other useful methods to help you pluck items out of the array.
Below we'll reference a few of the many useful methods available within the Cartalyst Collection
class.
first()
The first()
method can be used to retrieve the first element in the collection.
This will be the first element contained within the collection internal array.
$item = Cart::items()->first();
last()
The last()
method does the opposite of the first()
method and returns the last element contained within the collection internal array.
$item = Cart::items()->last();
isEmpty()
The isEmpty()
method can be used to check whether or not the collection has elements within it. It accepts no value and returns a boolean.
if ( ! Cart::items()->isEmpty())
{
echo 'We have items on our cart :)';
}
else
{
echo 'Cart is empty :(';
}
count()
The count()
method counts the number of items in the collection.
$total = Cart::items()->count();
Instances
Cart supports multiple cart instances, so that you can have as many shopping cart instances on the same page as you want without any conflicts.
You have two ways of accomplishing this, one is by creating a service provider dedicated to your wishlist to register all your other cart instances, the second method, which is easier, is to bind the new cart instances directly into the IoC.
IoC Binding
use Cartalyst\Cart\Cart;
use Cartalyst\Cart\Storage\Sessions\IlluminateSession;
$app = app();
$app['wishlist'] = $app->share(function($app)
{
$config = $app['config']->get('cartalyst/cart::config');
$storage = new IlluminateSession($app['session.store'], 'wishlist', $config['session_key']);
return new Cart($storage, $app['events']);
});
Create your Service Provider
app/services/WishlistServiceProvider.php
use Cartalyst\Cart\Cart;
use Cartalyst\Cart\Storage\Sessions\IlluminateSession;
use Illuminate\Support\ServiceProvider;
class WishlistServiceProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerSession();
$this->registerCart();
}
/**
* Register the session driver used by the Wishlist.
*
* @return void
*/
protected function registerSession()
{
$this->app['wishlist.storage'] = $this->app->share(function($app)
{
$config = $app['config']->get('cartalyst/cart::config');
return new IlluminateSession($app['session.store'], 'wishlist', $config['session_key']);
});
}
/**
* Register the Wishlist.
*
* @return void
*/
protected function registerCart()
{
$this->app['wishlist'] = $this->app->share(function($app)
{
return new Cart($app['wishlist.storage'], $app['events']);
});
}
}
Create your Facade
app/facades/Wishlist.php
use Illuminate\Support\Facades\Facade;
class Wishlist extends Facade {
protected static function getFacadeAccessor()
{
return 'wishlist';
}
}
Register your Service Provider and Facade
Open your Laravel config file app/config/app.php
and add the following lines.
In the $providers
array add the following service provider for this package.
'Path\To\Your\WishlistServiceProvider',
In the $aliases
array add the following facade for this package.
'Wishlist' => 'Path\To\Your\Wishlist',
Usage
Usage is identical to the cart.
Wishlist::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
]);
Conditions
The Cart package utilizes the Cartalyst Conditions package to manage item and cart based conditions.
The Cart has a default set of three condition types: discount
, tax
and other
conditions.
Applying Conditions
Cart Conditions
You can pass an array containing one or multiple conditions to the cart.
Apply a single condition
$condition = new Condition([
'name' => 'VAT (12.5%)',
'type' => 'tax',
'target' => 'subtotal',
]);
$condition->setActions([
[
'value' => '12.5%',
],
]);
Cart::condition($condition);
Apply multiple conditions
$conditionTax = new Condition([
'name' => 'VAT (12.5%)',
'type' => 'tax',
'target' => 'subtotal',
]);
$conditionTax->setActions([
[
'value' => '12.5%',
],
]);
$conditionDiscount = new Condition([
'name' => 'Discount (2.5%)',
'type' => 'discount',
'target' => 'subtotal',
]);
$conditionDiscount->setActions([
[
'value' => '-2.5%',
],
]);
Cart::condition([$conditionTax, $conditionDiscount]);
Item Conditions
You can add one or more (array) conditions to an item that will be assigned automatically when adding or updating items on the cart.
$condition = new Condition([
'name' => 'VAT (12.5%)',
'type' => 'tax',
'target' => 'subtotal',
]);
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
'conditions' => $condition,
]);
Removing Conditions
There will be times you'll need to remove conditions, in this section we'll cover how to remove specific conditions or all the conditions at once.
Cart::removeConditionByName()
Removes a condition by its name.
Param | Required | Type | Default | Description |
---|---|---|---|---|
$name | true | string | null | The condition name. |
$includeItems | false | boolean | true | Flag to either remove the condition from the items or not. |
Cart::removeConditionByName('Tax 10%');
Cart::removeConditionByType()
Removes a condition by its type.
Param | Required | Type | Default | Description |
---|---|---|---|---|
$type | true | string | null | The condition type. |
$includeItems | false | boolean | true | Flag to either remove the condition from the items or not. |
Cart::removeConditionByType('tax');
Cart::removeConditions()
Removes all conditions with the given identifier.
Param | Required | Type | Default | Description |
---|---|---|---|---|
$id | false | mixed | null | The condition identifier. |
$includeItems | false | boolean | true | Flag to either remove the condition from the items or not. |
$target | false | string | type | The target that the condition was applied on. |
Remove the condition with the type tax
.
Cart::removeConditions('tax');
Remove all the applied conditions
Cart::removeConditions();
Conditions Types
Conditions types are defined by the type property on conditions.
Cart handles discount, other and tax types by default.
Note: If you need to define custom condition types, make sure you set the conditions order using
Cart::setConditionsOrder($types)
by passing it an array of types that should be handled by the cart, otherwise only default condition types will be applied.
Tax
Tax conditions must have the type set to tax
$condition = new Condition([
'name' => 'VAT (12.5%)',
'type' => 'tax',
'target' => 'subtotal',
]);
$condition->setActions([
[
'value' => '12.5%',
],
]);
Discount
Discount conditions must have the type set to discount
$condition = new Condition([
'name' => 'Discount (5%)',
'type' => 'discount',
'target' => 'subtotal',
]);
$condition->setActions([
[
'value' => '-5%',
],
]);
The condition above will apply a 5% discount.
Other
Other conditions must have the type set to other
The condition below will add 5 to the subtotal after applying discounts (if any)
assuming conditions order are set to their default order.
$condition = new Condition([
'name' => 'Other (5%)',
'type' => 'other',
'target' => 'subtotal',
]);
$condition->setActions([
[
'value' => '5',
],
]);
Inclusive Conditions
Inclusive conditions are not added to the total but allow you to reverse
calculate taxes that are already included in your price.
This condition will be reverse calculated and will show up on total
conditions methods, but it will not be added to the cart total.
$condition = new Condition([
'name' => 'Tax (5%)',
'type' => 'tax',
'target' => 'subtotal',
]);
$condition->setActions([
[
'value' => '5%',
'inclusive' => true,
],
]);
Conditions Order
Default Order
- discount
- other
- tax
Get Cart Conditions Order
$order = Cart::getConditionsOrder();
Set Cart Conditions Order
Cart::setConditionsOrder([
'discount',
'other',
'tax',
'shipping',
]);
Set Items Conditions Order
Cart::setItemsConditionsOrder([
'discount',
'other',
'tax',
'shipping',
]);
Note: Make sure you set Item conditions before adding or updating.
# Condition targets
You can apply item conditions either on the item price or subtotal.
- price
- subtotal
Note 1: Item conditions are always applied prior to Cart conditions.
Note 2: Price-based item conditions are always applied prior to subtotal-based conditions.
Conditions Methods
Apply a condition.
Cart::condition(Cartalyst\Conditions\Condition $condition);
Return all applied conditions.
Cart::conditions($type|null, bool $includeItems);
Set the order in which conditions are applied.
Cart::setConditionsOrder([
'discount',
'other',
'tax',
]);
Set the order in which conditions are applied on items.
Cart::setItemsConditionsOrder([
'discount',
'tax',
'shipping',
]);
Return all conditions totals grouped by type.
Cart::conditionsTotal($type); // Returns an array of results of the type passed including items conditions
Cart::conditionsTotal($type, false); // Returns an array of results of the type passed excluding items conditions
Cart::conditionsTotal(); // Returns an array of results of all applied conditions including items conditions
Cart::conditionsTotal(null, false); // Returns an array of results of all applied conditions excluding items conditions
Return the sum of all or a specific type of conditions.
Cart::conditionsTotalSum($type); // Returns the sum of a the type passed
Cart::conditionsTotalSum(); // Returns the sum of all conditions
Return all conditions applied only to items.
Cart::itemsConditions();
Return all or a specific type of items conditions sum grouped by type.
Cart::itemsConditionsTotal($type); // Returns an array of results of the type passed
Cart::itemsConditionsTotal(); // Returns an array of results of all applied conditions
Return the sum of all or a specific type of items conditions.
Cart::itemsConditionsTotalSum($type); // Returns the sum of the type passed
Cart::itemsConditionsTotalSum(); // Returns the sum of all conditions
Serialization
Since v1.1, the Cart package supports serialization out of the box, allowing you to store a full shopping cart with all the information or the information you only need almost where you want and to retrieve it later for display and full usage.
Please read the following sections to learn how to serialize and unserialize the cart.
Serializable Properties
By default when calling the serialize();
method, we will serialize the following properties:
Property | Description |
---|---|
items | The items that are inside the cart. |
metaData | The meta data with custom information. |
conditions | The conditions. |
conditionsOrder | The conditions order. |
requiredIndexes | The required cart indexes. |
itemsConditionsOrder | The items conditions order. |
If you need to change these properties, you can use the setSerializable()
method.
Get the current Serializable Properties
$serializable = Cart::getSerializable();
Set the current Serializable Properties
Key | Required | Type | Description |
---|---|---|---|
properties | true | array | Array of properties that should be serializable. |
$properties = [
'items',
'conditions',
'conditionsOrder',
'itemsConditionsOrder',
];
$serializable = Cart::setSerializable($properties);
Serialize
Serializing the Cart is as easy as:
$cart = Cart::serialize();
Unserialize
Key | Required | Type | Description |
---|---|---|---|
$cart | true | string | A previously serialized cart. |
Unserializing is straightforward as well, all you need to provide is the serialized cart and that's it :)
# Using the serialized $cart from the previous example
Cart::unserialize($cart);
Events
On this section we have a list of all the events fired by the cart that you can listen for.
Event | Parameters | Description |
---|---|---|
cartalyst.cart.adding | $data, $cart | Event fired before an item is added to the cart. |
cartalyst.cart.added | $item, $cart | Event fired after an item is added to the cart. |
cartalyst.cart.removing | $item, $cart | Event fired before an item is removed from the cart. |
cartalyst.cart.removed | $item, $cart | Event fired after an item is removed from the cart. |
cartalyst.cart.updating | $item, $data, $cart | Event fired before an item in the cart is updated. |
cartalyst.cart.updated | $item, $cart | Event fired after an item is updated. |
cartalyst.cart.created | $cart | Event fired after the cart is created. |
cartalyst.cart.clearing | $cart | Event fired before the cart is cleared. |
cartalyst.cart.cleared | $cart | Event fired after the cart is cleared. |
Note: Please refer to the list below for the full event
parameter
object namespace.
Parameter | Description | Namespace |
---|---|---|
$item | The item object. | Cartalyst\Cart\Collections\ItemCollection |
$cart | The current cart instance object. | Cartalyst\Cart\Cart |
$data | The data that was passed. | array |
Examples
Whenever an item is about to be added to the shopping cart.
Event::listen('cartalyst.cart.adding', function(array $item, $cart)
{
// Apply your logic here
// Throw an exception to prevent the item from being added
});
Whenever an item is added to the shopping cart.
Event::listen('cartalyst.cart.added', function($item, $cart)
{
// Apply your own logic here
});
Whenever an item is about to be removed to the shopping cart.
Event::listen('cartalyst.cart.removing', function($item, $cart)
{
// Apply your logic here
// Throw an exception to prevent the item from being removed
});
Whenever an item is removed from the shopping cart.
Event::listen('cartalyst.cart.removed', function($item, $cart)
{
// Apply your own logic here
});
Whenever an item is about to be updated to the shopping cart.
Event::listen('cartalyst.cart.updating', function($item, $newData, $cart)
{
// Apply your logic here
// Throw an exception to prevent the item from being updated
});
Whenever an item is updated on the shopping cart.
Event::listen('cartalyst.cart.updated', function($item, $cart)
{
// Apply your own logic here
});
Whenever the shopping cart is about to be cleared.
Event::listen('cartalyst.cart.clearing', function($cart)
{
// Apply your logic here
// Throw an exception to prevent the cart from being cleared
});
Whenever the shopping cart is cleared.
Event::listen('cartalyst.cart.cleared', function($cart)
{
// Apply your own logic here
});
Change the status of the dispatcher
There might be situations where you will need to disable the event dispatcher.
To disable it just call Cart::setEventDispatcherStatus(false);
and to enable it just Cart::setEventDispatcherStatus(true);
.
You can also retrieve the current status of the event dispatcher by calling the Cart::getEventDispatcherStatus();
.
Exceptions
On this section we provide a list of all the exceptions that are thrown by the cart.
The exceptions are thrown in the Cartalyst\Cart\Exceptions
namespace.
Exception | Description |
---|---|
CartMissingRequiredIndexException | This exception will be thrown whenever a required index is not provided. |
CartInvalidQuantityException | This exception will be thrown when the provided quantity is invalid. |
CartInvalidPriceException | This exception will be thrown when the provided price is invalid. |
CartInvalidAttributesException | This exception will be thrown whenever the provided attributes are invalid or malformed. |
CartItemNotFoundException | This exception will be thrown whenever you request an item that does not exist. |
Examples
Catch the exception when adding an item into the cart with a missing required index.
try
{
# We're not passing the price
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
]);
}
catch (Cartalyst\Cart\Exceptions\CartMissingRequiredIndexException $e)
{
# Grabbing the missing index
$missingIndex = $e->getMessage();
// Apply your own logic here
}
Catch the exception when adding an item with an invalid quantity value.
try
{
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => -1,
'price' => 12.50,
]);
}
catch (Cartalyst\Cart\Exceptions\CartInvalidQuantityException $e)
{
// Apply your own logic here
}
Catch the exception when adding an item with an invalid price value.
try
{
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 'abc',
]);
}
catch (Cartalyst\Cart\Exceptions\CartInvalidPriceException $e)
{
// Apply your own logic here
}
Catch the exception when adding an item that contains invalid attributes.
try
{
Cart::add([
'id' => 'tshirt',
'name' => 'T-Shirt',
'quantity' => 1,
'price' => 12.50,
'attributes' => 'abc',
]);
}
catch (Cartalyst\Cart\Exceptions\CartInvalidAttributesException $e)
{
// Apply your own logic here
}
Catch the exception when trying to update an item that doesn't exist.
try
{
Cart::update('abc', [
'price' => 20.00,
]);
}
catch (Cartalyst\Cart\Exceptions\CartItemNotFoundException $e)
{
// Apply your own logic here
}