Knowing your potential buyers is the key to selling them effectively. Collecting the data of logged in customers provides you the important details to know who your customers are, what they want, and how to serve them better. Magento 2 store admin may want to implement certain features based on customer attributes of logged in users. For example, only logged in customers are allowed to view the price details. Admin may want to offer shipping services to particular customer groups only.
Customer attributes like age, location, gender can be handy for marketing insights. For example, you can target young customers as per their taste. Women may obviously not want to get suggestions for men’s trousers!
Admin needs to retrieve customer attributes value for such features. To get logged in customer data in Magento 2, one needs to follow one of the below methods.
Methods to get logged in customer data in Magento 2:
- using Object Manager1234$om = \Magento\Framework\App\ObjectManager::getInstance();$customerSession = $om->get('Magento\Customer\Model\Session');$customerData = $customerSession->getCustomer()->getData(); //get all data of customerData$customerData = $customerSession->getCustomer()->getId();//get id of customer
- using Block class123456789101112protected $customer;public function __construct(\Magento\Customer\Model\Session $customer,){$this->customer = $customer;}public function yourMethodName(){$customer = $this->customer;$customerName = $customer->getName();$customerId = $customer->getId();//You will get all basic detail with this $customer object}
Follow the above method and implement flawless features based on customer attributes!
Doubts regarding the topic are welcome in the comments section below and I’d be happy to help. ?
Flash 5 stars if the post has helped you to offer amazing features for your privileged customers ?
Happy Coding! ?
Get Weekly Updates
Never miss Magento tips, tricks, tutorials, and news.
Thank you for subscribing.
Something went wrong.
4 comments On How to Get Logged in Customer Data in Magento 2
Hi
I tried through rest API but not working. Can you provide solution to show logged in customer through rest api.
Hello Neeraj,
The API is different from the token you get from REST API.
Thanks.
Block class way is not working on magento 2.4 right ?
Hello Chamika,
It is working in Magento 2.4.
Thank you.