Using The Cart

Using The Cart

The Cart is available via the cart() function in the views.

Get Products in Cart

cart()->getItems() returns all products in the cart.

It returns an empty collection if the cart is empty.

Checking Whether A Cart Exists

A non-existing cart means that the current session has no cart.

cart()->exists() returns whether a cart exists for the current session.

cart()->doesNotExist() is the opposite of exists() 🤯

Example:

cart()->exists();
// false

cart()->addItem($product);

cart()->exists();
// true

Item Count

cart()->itemCount() returns the number of items in the cart.

It also returns 0 for non-existing carts.

Is Empty Or Not?

To have a cleaner code, there are two methods to check if cart is empty:

  • cart()->isEmpty()
  • cart()->isNotEmpty()

Adding Items To The Cart

Post requests to the URL returned by the add_to_cart_url() helper:

<form action="{{ add_to_cart_url($product) }}" method="post" class="mb-4">
    {{ csrf_field() }}

    <span class="mr-2 font-weight-bold text-primary btn-lg">
        {{ format_price($product->price) }}
    </span>
    <button type="submit" class="btn btn-success btn-lg"
        @if(!$product->price) disabled @endif>
        {{ __('Add to cart') }}
    </button>
</form>