I want to empty the cart before a product in the code. I tried


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')->getPath();
   $productObj = Product::load($productId);

   $product_variation_id = $productObj->get('variations')
   $storeId = $productObj->get('stores')->getValue()[0]['target_id'];
   $variationobj = \Drupal::entityTypeManager()
   $store = \Drupal::entityTypeManager()

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


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


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

    $response = new RedirectResponse(Url::fromRoute('commerce_cart.page')->toString());
    return $response;


You must use the commerce_cart.cart_manager service instead.

So $this->cartManager->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)) {
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.