Magento – How to load customer by attribute in magento2

customermagento-2.1magento2

What is the best way to load Customer by custom attribute?
I create custom module. What should I overwrite?

  • Model/Customer
  • Model/ResourceModel/Customer
  • Model/ResourceModel/CustomerRepository

What is the best way?

Best Answer

We should try with Service Contracts Layer.

Take a look: vendor/magento/module-backend/Model/Search/Customer::load()

    $searchFields = ['firstname', 'lastname', 'company'];
    $filters = [];
    foreach ($searchFields as $field) {
        $filters[] = $this->filterBuilder
            ->setField($field)
            ->setConditionType('like')
            ->setValue($this->getQuery() . '%')
            ->create();
    }
    $this->searchCriteriaBuilder->addFilters($filters);
    $searchCriteria = $this->searchCriteriaBuilder->create();
    $searchResults = $this->customerRepository->getList($searchCriteria);

We can use Magento\Customer\Api\CustomerRepositoryInterface::getList() to retrieve customers which match a specified criteria.

Related Topic