private $checkoutSession;
public function __construct(
\Magento\Checkout\Model\Session\Proxy $checkoutSession
) {
$this->checkoutSession = $checkoutSession;
}
public function getCartItemIds()
{
$cartItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
foreach($cartItems as $cartItem) {
echo $cartItem->getProductId(); //The entity_id of the product
echo $cartItem->getId(); //The entity_id of the cart item
}
}
This should help you understand how to best interact with the cart, assuming you are accessing this in the frontend
area.
Obtain the current checkoutSession
by injecting a Proxy
class for the Checkout\Model\Session
class. This prevents the session being loaded during class construction, and defers loading until it is called in the getCartItemIds()
method.
The checkoutSession->getQuote()
method will return an instance of Magento\Quote\Model\Quote
which has the getAllVisibleItems()
method. This method returns items that have not been deleted from the cart, and which do not have a parent (configurable options).
Each cart item has a product_id
and an entity_id
. These two fields are different, as one is the identifier for the quote_item
record and one is the entity_id
of the catalog_product_entity
record it relates to, as shown in the example.
Be sure to run bin/magento setup:di:compile
to generate the Proxy
class if needed.