How to Get Magento 2 Collection Count
Collections in Magento 2 are used to fetch multiple rows from tables, join tables with primary tables, select specific columns, apply a WHERE clause to query, or apply any conditions.
A store owner may want to use collections to print order details with header and footer when the number of orders is greater than 0 and for no orders, i.e., 0 orders, display a message “No record found” without a header and footer.
In such scenarios, one may need to get Magento 2 collection count.
Return the total number of items from the collection, i.e., count the collection data using the below solution:
Method to Get Magento 2 Collection Count
Here we are using an example of fetching all products and count these all fetched data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; protected $productCollectionFactory; public function __construct(CollectionFactory $productCollectionFactory) { $this->productCollectionFactory = $productCollectionFactory; } public function getProductCollection() { $collection = $this->productCollectionFactory->create(); $collection->addAttributeToSelect('*'); return $collection; } |
We have got a whole collection of products using the above code, now call the getProductCollection() wherever you want to use the collection.
1 |
$collection = $this->getProductCollection(); |
Now the main part, count the items collected in $collection by using the below code.
1 |
$collection->count(); |
You can apply various validations, conditions, or anything according to your requirements using the collection count method.
That’s all!
If you have any doubts regarding this post, just mention them in the Comments section below.
I would be happy to help.
Feel free to share the solution with Magento Community via social media.
Thank You.
Jignesh Parmar
An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.
2 Comments
I would like to know which page should i can change and get the product count.
Hello Shaima,
You don’t need to change any page.
the count will provide the count of collection.
Thank You