Skip to main content

Magento 2: Loading a Customer by a Custom Attribute

Magento 2: Loading a Customer by a Custom Attribute

Hello Magento Developers!

In Magento 2, retrieving customer information is a fundamental task, and often you need to do it based on something other than the standard customer ID or email. Whether you've added a custom attribute like a 'loyalty ID' or a 'phone number', knowing how to efficiently load a customer by that specific attribute is a crucial skill.

In this post, we'll explore two primary methods for this task and a bonus tip for working with EAV attributes.


Method 1: Using the Customer Collection

This is a very common and straightforward approach. It leverages Magento's collection system to filter and retrieve customer data. This method is great for quick lookups and is easy to understand.

Code Breakdown:

  • CollectionFactory $customerCollectionFactory: We inject the factory to create a new customer collection object.

  • addAttributeToSelect('*'): This fetches all customer attributes. For better performance on large datasets, you can specify only the attributes you need (e.g., ['firstname', 'lastname', 'email']).

  • addAttributeToFilter($attributeCode, $attributeValue): This is the core of our search, filtering the collection to find customers where the attribute code matches the specified value.

  • setPageSize(1) & getFirstItem(): We optimize the query by limiting the result to a single customer and then getting the first item from the collection.



        <?php


        namespace YourCompany\YourModule\Model;


        use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;

        use Magento\Framework\Api\SearchCriteriaBuilder;


        class CustomerLoader

        {

            protected $customerCollectionFactory;

            protected $searchCriteriaBuilder;


            public function __construct(

                CollectionFactory $customerCollectionFactory,

                SearchCriteriaBuilder $searchCriteriaBuilder

            ) {

                $this->customerCollectionFactory = $customerCollectionFactory;

                $this->searchCriteriaBuilder = $searchCriteriaBuilder;

            }


            public function loadCustomerByCustomAttribute($attributeCode, $attributeValue)

            {

                $collection = $this->customerCollectionFactory->create()

                    ->addAttributeToSelect('*') // Select all customer attributes

                    ->addAttributeToFilter($attributeCode, $attributeValue); // Filter by your custom attribute


                // You can add a limit if you expect only one customer

                $collection->setPageSize(1); 


                $customer = $collection->getFirstItem();


                if ($customer->getId()) {

                    return $customer;

                }


                return null; // Customer not found

            }

        }








        <?php


        namespace YourCompany\YourModule\Model;


        use Magento\Customer\Api\CustomerRepositoryInterface;

        use Magento\Framework\Api\SearchCriteriaBuilder;

        use Magento\Framework\Api\FilterBuilder;


        class CustomerRepositoryLoader

        {

            protected $customerRepository;

            protected $searchCriteriaBuilder;

            protected $filterBuilder;


            public function __construct(

                CustomerRepositoryInterface $customerRepository,

                SearchCriteriaBuilder $searchCriteriaBuilder,

                FilterBuilder $filterBuilder

            ) {

                $this->customerRepository = $customerRepository;

                $this->searchCriteriaBuilder = $searchCriteriaBuilder;

                $this->filterBuilder = $filterBuilder;

            }


            public function loadCustomerByCustomAttribute($attributeCode, $attributeValue)

            {

                $filter = $this->filterBuilder

                    ->setField($attributeCode)

                    ->setValue($attributeValue)

                    ->setConditionType('eq') // 'eq' for equals, 'like' for partial match, etc.

                    ->create();

                $searchCriteria = $this->searchCriteriaBuilder

                    ->addFilters([$filter])

                    ->create();


                $customerList = $this->customerRepository->getList($searchCriteria)->getItems();

                if (!empty($customerList)) {

                    return reset($customerList); // Get the first customer from the list

                }

                return null; // Customer not found

            }

        }





    namespace YourVendor\YourModule\Model; // Adjust namespace accordingly

    use Magento\Eav\Model\Config;

    class YourClass

    {

        protected $eavConfig;

        public function __construct(

            Config $eavConfig

        ) {

            $this->eavConfig = $eavConfig;

        }


        public function getCustomerPhoneNumberAttributeId()

        {

            $attribute = $this->eavConfig->getAttribute('customer', 'phone_number');

            $attributeId = $attribute->getAttributeId();

            return $attributeId;

        }

    }

    ?>

Comments

Popular posts from this blog

Magento 2 how to create frontend route

app\code\Vendor\Module\etc\routes.xml app\code\Controller/Index/Login.php scopeConfig = $scopeConfig; } public function execute() { $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE); $resultPage->getConfig()->getTitle()->set(__('Mobile Login')); return $resultPage; } } app\code\Vendor\Module\view\frontend\layout\mobilelogin_index_login.xml app\code\Vendor\Module\view\frontend\templates\login.phtml your code

latest about YO YO

Most Famous among youth, yo yo honey singh's full name is Hiresh singh. He was born on 15 mar 1983 in Delhi. he is a popular rapper, music producer, singer and actor. Recently Honey singh will be seen in upcoming movie "X pose". In this movie, he has played a negative role. According to Yo Yo, he has a little copied the famous actor Pran in it.