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:
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()); } }
That’s it.
Please share the solution with the Magento community via social media.
Thank you.