How to Get Customer ID Without Using Session in Magento 2
Magento developers often use customer ID to implement features that are exclusively for logged in customers. Even I have posted solutions where one can get customer addresses by customer ID in Magento 2 and use it to maintain the address database while offering guest checkout. Magento 2 provides a convenient way to get, set, and unset custom session variables using the session object.
Apart from this, the admin may need a customer ID to hide the signup button for already logged in customers, or display a discount offer that is valid only for logged in customers!
I can go one with the examples where a Magento developer will require to get a customer ID. But today, instead I am going to offer an alternate solution to get a customer ID.
You can get customer ID without using session in Magento 2 and hence avoid issues like
- A NULL value is returned even if the customer is logged in.
- You have to disable the cache, and hence low page speed.
- It does not return customer ID.
That’s why I recommend using the below solution which does not generate any issues and doesn’t require disabling cache.
Method to Get Customer ID Without Using Session in Magento 2
Use the below code in the helper file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php namespace Vendor\Extension\Helper; use Magento\Authorization\Model\UserContextInterface; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; class Data extends AbstractHelper { protected $userContext; public function __construct( Context $context, UserContextInterface $userContext ) { $this->userContext = $userContext; parent::__construct($context); } public function getLoginCustomerId() { $customerId = $this->userContext->getUserId(); return $customerId; } } |
That’s all!
If you have any doubts regarding this post, just mention them in the Comments section below.
I would be happy to help.
Feel free to share the solution with Magento Community via social media.
Thank You.
Chandresh Chauhan
He has been with Meetanshi for more than three years now as a certified Magento developer. A silent guy whom you can always find solving clients' issues, is an avid reader too.
Prev
How to Login Customer Programmatically Without Password in Magento 2
How to Customize Email Templates in Magento 2
Next