jared0430 / cart
A simple session based cart for Laravel 5 intended for use with an existing Product model
Requires
- php: >=5.4.0
- illuminate/support: ~5.0
This package is not auto-updated.
Last update: 2018-03-28 13:28:43 UTC
README
A simple session based cart for Laravel 5.1+ intended for use with an existing Product model.
Requirements
- Laravel 5.1+
Installation
Require this package with composer by using composer require jared0430/cart ~1.1
or by adding it to composer.json
{ "require": { "jared0430/cart": "~1.1" } }
After updating composer, add the service provider to the providers
array in config/app.php
Jared0430\Cart\CartServiceProvider::class,
and add the facade to the aliases
array in config/app.php
'Cart' => Jared0430\Cart\Facades\Cart::class,
Changing the session key
By default it uses cart
as the session key. You can change this by publishing the config file
php artisan vendor:publish
This will create a new config file cart.php
Methods
add
Add a product to the cart, adding to the quantity if it already exists
Cart::add((int)$product_id, (int)$quantity_to_add);
subtract
Subtract from the quantity of a product in the cart
Cart::subtract((int)$product_id, (int)$quantity_to_subtract);
update
Directly modify the quantity of a product. You can choose whether to add to the quantity or directly replace it with the $add
parameter
Cart::update((int)$product_id, (int)$quantity, (bool)$add);
remove
Completely remove a product from the cart
Cart::remove((int)$product_id);
has
Determine if a product is in the cart or not
Cart::has((int)$product_id);
Returns true
or false
products
Get a list of all items in the cart
Cart::products();
Returns an instance of Collection
count
Get the total number of unique items in the cart
Cart::count();
Returns an int
countQty
Get the total number of items in the cart
Cart::countQty();
Returns an int
clear
Empties the cart
Cart::clear();
Events
An event is fired whenever the cart is updated so you can hook in to perform your own logic.
To listen for this event you need to register a new Listener
in App\Providers\EventServiceProvider
protected $listen = [ 'Jared0430\Cart\Events\CartWasUpdated' => [ 'App\Listeners\MyCartListener' ] ];
Now run php artisan event:generate
which will create App\Listeners\MyCartListener
Note that Laravel incorrectly references Jared0430\Cart\Events\CartWasUpdated
as App\Events\Jared0430\Cart\Events\CartWasUpdated
so you will need to correct this
You can access the cart in this listener's handle
method by using $event->cart
which returns an instance of Collection