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!
Best Answer
You can directly get the total qty of
quote
without usingforeach
by using this method$quote->getItemsQty();
If you want to check in
order
object then you can get it by,$order->getTotalQtyOrdered()
Where
$quote
isMagento\Quote\Model\Quote
object and$order
isMagento\Sales\Model\Order
object.