Hello Magento Friends?,
How are you all developing? As always today I will help you out How to get Customer Collection in Magento 2. Also, go through the previously placed article How to Get Product Stock Information in Magento 2. Let’s Dive In?
Introduction:
With the help of customer collection, one can filter all the store’s customer’s information by attributes. The customer’s information is very essential information Hence, in this article I will help you to get Customer Collection in Magento 2.
Steps to Get Customer Collection in Magento 2:
Method 1: Using Class
Create one block file on our custom extension add Blockname.php in the following path
app\code\Vendor\Extension\Block\Blockname.php
now add following code,
<?php namespace Vendor\Extension\Block; use Magento\Framework\View\Element\Template; class Blockname extends Template { protected $_customer; protected $_customerFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Customer\Model\CustomerFactory $customerFactory, \Magento\Customer\Model\Customer $customers ) { $this->_customerFactory = $customerFactory; $this->_customer = $customers; parent::__construct($context); } public function getCustomersCollection() { return $this->_customer->getCollection() ->addAttributeToSelect("*") ->load(); } public function getFilteredCustomersCollection() { return $this->_customerFactory->create()->getCollection() ->addAttributeToSelect("*") ->addAttributeToFilter("firstname", array("eq" => "Max")) -load(); } }
after this, you need to phtml file and add following code into the file,
var_dump($block->getCustomersCollection()); var_dump($block->getFilteredCustomersCollection());
Method 2: Using Object Manager
$customerID = 10; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customer = $objectManager->create('Magento\Customer\Model\Customer') ->load($customerID); $customerEmail = $customer->getEmail();
That’s It.
Note: Using ObjectManager for Magento development is not recommended by us and Magento. This is just for Knowledge purposes.
Conclusion:
With the help of the above-given steps, you will be easily getting the customer collection. If you find any type of difficulties in the above-given solution then do share in the comment section below. Also, share the blog with your developer friends and make yourself helpful.
Happy Coding!