How do I programmatically empty a cart? I want to empty the cart before a product in the code. I tried

$this-&gt;cartProvider-&gt;emptyCart($cart);

But this did not work and gave an error. I am doing this in Drupal 8. I am adding products in the controller code.

This is how I am fetching the cart.

$destination = \Drupal::service('path.current')-&gt;getPath();
   $productObj = Product::load($productId);

   $product_variation_id = $productObj-&gt;get('variations')
     -&gt;getValue()[0]['target_id'];
   $storeId = $productObj-&gt;get('stores')-&gt;getValue()[0]['target_id'];
   $variationobj = \Drupal::entityTypeManager()
     -&gt;getStorage('commerce_product_variation')
     -&gt;load($product_variation_id);
   $store = \Drupal::entityTypeManager()
     -&gt;getStorage('commerce_store')
     -&gt;load($storeId);



     $cart = $this-&gt;cartProvider-&gt;getCart('default', $store);

     $this-&gt;cartManager-&gt;emptyCart($cart);

   if (!$cart) {
    $cart = $this-&gt;cartProvider-&gt;createCart('default', $store);

   }

   $line_item_type_storage = \Drupal::entityTypeManager()
     -&gt;getStorage('commerce_order_item_type');
// Process to place order programatically.
   $cart_manager = \Drupal::service('commerce_cart.cart_manager');
   $line_item = $cart_manager-&gt;addEntity($cart, $variationobj);

    $response = new RedirectResponse(Url::fromRoute('commerce_cart.page')-&gt;toString());
    return $response;
You must use the commerce_cart.cart_manager service instead.

So $this-&gt;cartManager-&gt;emptyCart($cart); should do the trick.

Update: The reason why you get an error is because you try to call emptyCart on $cart then it's NULL.

You must wrap the line where you empty the cart in an if statement, like this:

if (!empty($cart)) {
  $this-&gt;cartManager-&gt;emptyCart($cart);
}