1

After logged in Magento frontend. I need to get ID of user on which account I am currently logged in.

Please help.

1

2 Answers 2

3

Try with changing the session object

 <?php
namespace YourCompanyName\YourModuleName\Block;
class YourCustomBlock extends \Magento\Framework\View\Element\Template
{
    protected $_customerSession;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Model\SessionFactory $customerSession,
        array $data = []
    ) {
        $this->_customerSession = $customerSession->create();
        parent::__construct($context, $data);
    }

    public function getLoggedinCustomerId() {
        if ($this->_customerSession->isLoggedIn()) {
            return $this->_customerSession->getId();
        }
        return false;
    }

    public function getCustomerData() {
        if ($this->_customerSession->isLoggedIn()) {
            return $this->_customerSession->getCustomerData();
        }
        return false;
    }
}

Now, we can use the functions in our view (.phtml) file as follows.

$customerId = $block->getLoggedinCustomerId();
echo 'Customer Id: ' . $customerId;

$customerData = $block->getCustomerData();
if($customerData) {
    echo 'Customer Id: ' . $customerData->getId() . '<br/>';
    echo 'Customer Name: ' . $customerData->getName() . '<br/>';
    echo 'Customer Email: ' . $customerData->getEmail() . '<br/>';
    echo 'Customer Group Id: ' . $customerData->getGroupId() . '<br/>';
}

Try with objectmanger

$om = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $om->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
    $customerSession->getCustomer()->getId();
    $customerSession->getCustomer()->getName(); 
    $customerSession->getCustomer()->getEmail();
    $customerSession->getCustomer()->getGroupId(); // get Customer Group Id
}
0

You can use this below code in your block file :

protected $customerSession;

/**
 * Construct
 *
 * @param \Magento\Framework\View\Element\Template\Context $context
 * @param \Magento\Customer\Model\Session $customerSession
 * @param array $data
 */
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Customer\Model\Session $customerSession,
    array $data = []
) {
    parent::__construct($context, $data);

    $this->customerSession = $customerSession;
}

public function getCustomerId()
{
    $customerId = '';
    if($this->customerSession->isLoggedIn()){
        $customerId = $this->customerSession->getCustomer()->getId();
    }
    return $customerId;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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