In this post I am going to explain how to get list of all customers or you can say customer collection in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | protected $_customerFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Customer\Model\CustomerFactory $customerFactory, array $data = [] ) { $this->_customerFactory = $customerFactory; parent::__construct($context, $data); } public function getCustomerCollection() { $collection = $this->_customerFactory->create()->getCollection() ->addAttributeToSelect("*") ->load(); return $collection; } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 10 | //Get customer collection $customerCollection = $block->getCustomerCollection(); if ($customerCollection && count($customerCollection) > 0) { foreach ($customerCollection AS $customer) { echo $customer->getFirstname()."<br/>"; echo $customer->getLastname()."<br/>"; echo $customer->getEmail()."<br/>"; } } |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerFactory = $objectManager->create('Magento\Customer\Model\CustomerFactory')->create(); //Get customer collection $customerCollection = $customerFactory->getCollection() ->addAttributeToSelect("*") ->load(); if ($customerCollection && count($customerCollection) > 0) { foreach ($customerCollection AS $customer) { echo $customer->getFirstname() . "<br/>"; echo $customer->getLastname() . "<br/>"; echo $customer->getEmail() . "<br/>"; } } |
Thats it. Enjoy Magento 2!!
Leave a Reply