How To Get Customer Data From Attribute Value In Magento 2
Magento 2 is a preferable choice for E-commerce stores, owing to the flexibility and customization options it offers. One such example is posted here that allows to get customer data from attribute value in Magento 2.
As online stores evolve, offering advanced features is a must. One such similar situation was the case in a client’s store where I needed to get the customer’s data from the attribute value even when it is not stored in the session, i.e., the customer is not logged in.
Similarly, you can use the below solution to build advanced functionalities where you need to get the customers’ data when it is not stored in the session, but only using the attribute value.
In the below code, if the attribute value is unique per customer, one customer data is obtained, else the collection of customers’ data is obtained for that attribute value.
Method To Get Customer Data From Attribute Value In Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory; protected $customerFactory; public function __construct(CollectionFactory $customerFactory) { $this->customerFactory = $customerFactory; } public function getCustomerByAttirbute($val) { try { $customer = $this->customerFactory->create() ->addAttributeToSelect("*") ->addAttributeToFilter("attribute_code", ["eq" => $val]) ->getFirstItem(); return $customer; } catch (\Exception $e) { $this->_logger->info("Error" . $e->getMessage()); } } |
Any issues in the above method?
Feel free to post them in the Comments section below. I’d be happy to help.
Please share the solution with the Magento community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How To Add A Column To Existing Database Table In Magento 2
How To Remove Insert Variable & Insert Widget From WYSIWYG Editor In Magento 2
Next