0

I tried to get customer id from default.phtml in /vendor/magento/module-catalog/view/frontend/templates/product/view/type, but when I use $_SESSION['customer_base'], the customer_id is NULL like in the picture below. How can I get the current logged in customer id ?

enter image description here

3

1 Answer 1

7

Try this

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

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

if($customerSession->isLoggedIn()){
  echo $customerSession->getCustomerId();
}

Method 2:

....

protected $_customerSessionFactory;

public function __construct(
    .....
    \Magento\Customer\Model\SessionFactory $customerSessionFactory,
    .....
    .....
) {
    .....
    $this->_customerSessionFactory = $customerSessionFactory;
    .....
    .....
}

....
....

$customerSession = $this->_customerSessionFactory->create();
$customer = $customerSession->getCustomer();
2
  • I can get ID in controller by this but it returns nothing in model class, cache is disabled
    – Ajwad Syed
    Aug 18, 2019 at 13:30
  • Check my updated code Aug 23, 2019 at 9:49

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