-
Notifications
You must be signed in to change notification settings - Fork 2
Instances and models
The packages supports multiple instances of the cart. The way this works is like this:
You can set the current instance of the cart by calling Cart::instance('newInstance')
. From this moment, the active instance of the cart will be newInstance
, so when you add, remove or get the content of the cart, you're 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, ['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 default
, so when you're not using instances,Cart::content();
is the same as Cart::instance('default')->content()
.
Because it can be very convenient to be able to directly access a model from a CartItem is it possible to associate a model with the items in the cart. 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 right from the CartItem
!
The model can be accessed via the model
property on the CartItem.
If your model implements the Buyable
interface and you used your model to add the item to the cart, it will associate automatically.
Here is an example:
// First we'll add the item to the cart.
$cartItem = Cart::add('293ad', 'Product 1', 1, 9.99, ['size' => 'large']);
// Next we associate a model with the item.
Cart::associate($cartItem->rowId, 'Product');
// Or even easier, call the associate method on the CartItem!
$cartItem->associate('Product');
// You can even make it a one-liner
Cart::add('293ad', 'Product 1', 1, 9.99, ['size' => 'large'])->associate('Product');
// Now, when iterating over the content of the cart, you can access the model.
foreach(Cart::content() as $row) {
echo 'You have ' . $row->qty . ' items of ' . $row->model->name . ' with description: "' . $row->model->description . '" in your cart.';
}