Hello Everyone,
In this blog, we will learn about how to get Customer Collection in Magento 2.
With the help of customer collection, we can filter all store’s customer’s information.
Customer information is very important.
Without wasting your time, let us guide you straight away. Follow the easy step given below to get Customer Collection in Magento 2.
STEPS FOR GET CUSTOMER COLLECTION IN MAGENTO 2
Step 1: Create CustomerData.php file
app/code/Vendor/Extension/Block/CustomerData.php
<?php
namespace Vendor\Extension\Block;
use Magento\Framework\View\Element\Template;
class CustomerData 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" => "Demo"))
-load();
}
}
Step 2: Create CustomerData.phtml file
app/code/Vendor/Extension/view/frontend/templates/CustomerData.phtml
<?php
$customersCollection = $block->getCustomersCollection(); ?>
<?php foreach ($customersCollection as $customer): ?>
<?php echo $customer->getFirstname(); ?>
<?php echo $customer->getLastname(); ?>
<?php endforeach; ?>
$customersFilteredCollection = $block->getFilteredCustomersCollection(); ?>
Step 3: Finally run the below commands
$ php bin/magento cache:clean
$ php bin/magento cache:flush
Final Thoughts:
So this was the easiest way which we have told you in this blog. This is how you can get Customer Collection in Magento 2. Hope you liked the blog.
So quickly go to the comment box and tell me how you like this blog?
Stay tuned with us on our site to get new updates of Magento.
Thanks for reading and visiting our site.
