1

I am trying to get the items of the cart as well as the customer ID in my Module. But the problem is that I don't know how to get the customer ID properly.

In the Moment I have this Code and it works:

<?php
// Get all items in cart
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');

// retrieve quote items collection
$itemsCollection = $cart->getQuote()->getItemsCollection();

// get array of all items what can be display directly
$itemsVisible = $cart->getQuote()->getAllVisibleItems();

// retrieve quote items array
$items = $cart->getQuote()->getAllItems();

foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'<br />';
    echo 'Name: '.$item->getName().'<br />';
    echo 'Sku: '.$item->getSku().'<br />';
    echo 'Quantity: '.$item->getQty().'<br />';
    echo 'Price: '.$item->getPrice().'<br />';
    echo "<br />";
}

Now, what do I need to add to get the Customer ID?

1

This should be the right code:

$customerSession = $objectManager->create("Magento\Customer\Model\Session");

  echo $customerSession->getCustomerId();

By using this great code it should work.

Therefore, the customer ID will get returned to you.

New contributor
Pave is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
2

Please try with below code...

$customerSession = $objectManager->create("Magento\Customer\Model\Session");

  echo $customerSession->getCustomerId();

I hope its work for you.

  • 1
    Thank you very much, it works. You are the best. – felix Aug 8 at 6:55
  • Using observer, how to do that? – zus Aug 8 at 7:04
  • using observer, also try same code. – Anas Mansuri Aug 8 at 7:05
0

You can try this code:

public function getCustomerId(){
    $session = $this->objectManager->get('Magento\Customer\Model\Session');    
    return $session->getCustomer()->getId();
}

Here, firstly you need to check customer is logged in or not:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
echo 'Customer ID: '.$this->getCustomerId();   
}

Hope this will be better solution.

0

You can use method getCustomerSession() in \Magento\Checkout\Model\Cart to get customer data.

$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$customerId = $cart->getCustomerSession()->getCustomerId();

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.