<blockquote>
  <p>Is caching by cart.id sufficient?</p>
</blockquote>

<p>I would not cache the cart, it could always be changing. You would need to create a cache ID based on every aspect of the cart that could change (line items, coupons, addresses, sales, discounts, tax etc). Bottom line, do not cache dynamic things like the cart.</p>

<blockquote>
  <p>Is there any potential risk?</p>
</blockquote>

<p>See above.</p>

<blockquote>
  <p>What is {% set cart = craft.commerce.cart %} actually setting when cart.id = null ?</p>
</blockquote>

<p>You are getting an order model returned, it just does not get an ID until the first item is added to the cart and the order/cart is saved to the database.</p>

CC BY-SA 3.0
2016-09-29T11:34:38.103Z
2016-09-29T11:55:30.377Z
2016-09-29T11:55:30.377Z
Luke Holder
<p>I want to cache the cart using key <code>cart.id</code> to save some db queries.</p>

<pre><code>{% set cart = craft.commerce.cart %}

{% cache globally using key "cartId=" ~ cart.id ?? "empty" until cart.dateUpdated %}

{% if cart.lineItems | length %}
    {% for item in cart.lineItems %}
        {{ item.sku }},
    {% endfor %}
{% else %}
    &lt;p&gt;Cart has no items&lt;/p&gt;
{% endif %}

{% endcache %}
</code></pre>

<ol>
<li>Is caching by cart.id sufficient?</li>
<li>Is there any potential risk?</li>
<li>What is <code>{% set cart = craft.commerce.cart %}</code> actually setting when cart.id = null ?</li>
</ol>

<plugin-craftcommerce>
Cache cart globally using key cart.id
# Cache cart globally using key cart.id

(Asked by: username_0 on 2016-09-29)

I want to cache the cart using key cart.id to save some db queries.
{% set cart = craft.commerce.cart %}

{% cache globally using key "cartId=" ~ cart.id ?? "empty" until cart.dateUpdated %}

{% if cart.lineItems | length %}
    {% for item in cart.lineItems %}
        {{ item.sku }},
    {% endfor %}
{% else %}
    Cart has no items
{% endif %}

{% endcache %}


Is caching by cart.id sufficient?
Is there any potential risk?
What is {% set cart = craft.commerce.cart %} actually setting when cart.id = null ?

**Tags:** plugin-craftcommerce


---

## 1 answers

### Answer by username_1 on 2016-09-29. Score: 5 | Accepted answer

> Is caching by cart.id sufficient?

I would not cache the cart, it could always be changing. You would need to create a cache ID based on every aspect of the cart that could change (line items, coupons, addresses, sales, discounts, tax etc). Bottom line, do not cache dynamic things like the cart.

> Is there any potential risk?

See above.

> What is {% set cart = craft.commerce.cart %} actually setting when cart.id = null ?

You are getting an order model returned, it just does not get an ID until the first item is added to the cart and the order/cart is saved to the database.


---

