Hello Magento Developers,
In this blog post, we are going to guide you How to get Customer Collection in Magento 2. Also, go through the last blog How to Get Admin User Data in Magento 2.
The customer’s information is very basic information. you can filter all the store’s customer’s information by attributes, with the guidance of customer collection. Now let’s see how to get Customer Collection in Magento 2.
Steps to Get Customer Collection in Magento 2:
Firstly, We create one block file on our custom module in the following path:
app\code\Webiators\CustomerCollection\Block\Collection.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php namespace Webiators\CustomerCollection\Block; use Magento\Framework\View\Element\Template; class Collection 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(); } } |
Then, you need to create phtml file and add following code,
app\code\Webiators\CustomerCollection\view\frontend\templates\getcollection.phtml
1 2 3 4 5 6 7 8 9 10 |
<?php $custID = 5; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerObj = $objectManager->create('Magento\Customer\Model\Customer') ->load($custID); $customerEmail = $customerObj->getEmail(); $customerFirstName = $customerObj->getFirstname(); echo "customer email" ." ". $customerEmail; echo "customer FirstName" ." ". $customerFirstName; ?> |
If you want to call phtml file on the product page then you can create a layout file to achieve this.
Create a layout file in your module in the following path: app\code\Webiators\CustomerCollection\view\frontend\layout\catalog_product_view.xml
Put the following code in layout file
1 2 3 4 5 6 7 8 |
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="content"> <block class="Magento\Framework\View\Element\Template" name="getcollection" template="Webiators_CustomerCollection::getcollection.phtml" /> </referenceContainer> </body> </page> |
That’s It!
Hopefully, with the help of the above steps, you will be easily getting the customer collection in Magento2. But if you face any problems in this do write it in the comment section below.
Happy Coding!