0

I want to get total quantity of product added in cart by product ID. I use \Magento\Checkout\Model\Cart class to get all items in cart.

$items = $cart->getQuote()->getAllItems();

foreach ($items as $item) {
    if ($item->getProductId() == '101') {
        return $item->getQty(); //Get product qty
    }
}

This will get product qty added in cart. But if I have 30 products in cart it will loop 30 times.

Is there any way to get qty of single product without looping all products from cart?

Any help appreciated!

  • If u can get the total collection of cart items, then u can sort it by using required Product ID. From that you can get the required quantity.. – Pavan Kumar Jul 6 '17 at 7:15
  • 1
    @PavanKumar Can you provide code. – Prince Patel Jul 6 '17 at 7:31
2

You can directly get the total qty of quote without using foreach by using this method

$quote->getItemsQty();

If you want to check in order object then you can get it by,

$order->getTotalQtyOrdered()

Where $quote is Magento\Quote\Model\Quote object and

$order is Magento\Sales\Model\Order object.

1
//add code in list.phtml
<div>
    <?php
    $IdDoProduto = $_product->getId();
    $cart = $this->helper('\Magento\Checkout\Helper\Cart');
    $itens = $cart->getQuote()->getItems();

    foreach ($itens as $item){
        if($IdDoProduto == $item->getProduct_id()){
            echo $item->getQty();
        }
    }
    ?>
</div>
0

You can get item qty from bellow code it will check for the product in current item collection and return qty if product is available...

$items = $cart->getQuote()->getAllItems();
$productId="your_product_id";
foreach ( $items as $item) {
        if ($item->getProductId() == $productId) {
            return $item->getQty();
        }
    }
  • I know how to get all products from cart. I already declare in question. I want to get product qty by product ID. – Prince Patel Jul 6 '17 at 7:29
  • it will return you product Qty.. check the code I have added condition for check productID and if product ID match with the Item collection Product ID it will return only product Qty not full Item collection – Emipro Technologies Pvt. Ltd. Jul 6 '17 at 7:32
  • I mean $cart->getQuote()->getAllItems() this function get all items from cart and we need foreach to load each item. but I don't won't foreach to load all items. For ex. I have 50 product in cart then it will loop 50 times. – Prince Patel Jul 6 '17 at 8:02

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.