
How to get current logged in customer data in Magento 2
While working on Magento several times we need to get the details of current logged in customer. It can easily be checked whether the customer is logged in or not. If the customer is logged in then we can retrieve its data and use it for our functionality implementation.
Magento uses session to store current logged in customer. We can use the Magento\Customer\Model\Session class to get logged in customer. Below is the code snippet which will return the customer data if customer is logged in.
<?php
namespace WebbyTroops\Customer\Block;
class Customer extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Customer\Model\Session
*/
protected $_customerSession;
/**
* @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 = []
) {
$this->_customerSession = $customerSession;
parent::__construct($context, $data);
}
/**
* Get logged in Customer
*/
public function getLoggedInCustomer()
{
if ($this->_customerSession->isLoggedIn()) {
return $this->_customerSession->getCustomer();
}
return false;
}
}
Get Logged In Customer in template file
Now you can easily access the logged in customer data in you phtml file.
$customer = $block->getLoggedInCustomer();
if ($customer) {
$email = $customer->getId();
$email = $customer->getEmail();
$firstName = $customer->getName();
}
If you want to get logged in customer in the REST API by bearer token then follow this article.
Related Posts
Leave a Reply Cancel reply
Categories
- Digital Marketing (7)
- eCommerce (34)
- Laravel (1)
- Latest News (5)
- Magento 2 Extensions (5)
- Magento2 (38)
- Shopify (5)
- Shopware (7)
- Wordpress (2)
Recent Posts
Advanced custom links extension (1) auto cancel order (1) banners (1) cancel order (1) cart attributes (1) Customer (7) Custom order invoice number module (1) custom shipping method (1) E-Commerce (7) eCommerce (41) full page cache magento 2 (1) hcaptcha (1) hcaptcha vs recaptcha (1) How to add customer attribute in Magento 2 (1) Laravel 10 (1) Magento2 (34) magento 2 back in stock notification (1) magento 2 cancel order (1) Magento2 Extension (3) magento 2 extensions (1) magento 2 layered navigation (1) magento 2 recaptcha (2) magento 2 robots.txt (1) magento 2.4.6 (1) magento headless commerce (1) new features (1) online store (13) openmaze (1) order management (1) Product (4) product attributes (1) recaptcha (1) search engine optimization (6) seo (10) shipping rule (1) shopify (3) shopware (6) Shopware-plugin (3) Shopware 6 (5) shopware 6 released (1) store switcher (1) structured data (1) upcoming update (1) wordpress (1) wordpress vs shopify (1)