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.
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.
$collection = $this->getProductCollection();
Now the main part, count the items collected in $collection by using the below code.
$collection->count();
You can apply various validations, conditions, or anything according to your requirements using the collection count method.
Also remember when working with Magento 2 collections, it’s important to not only get the collection count but also manage the number of items per page using setPageSize in Magento 2 efficiently.
That’s all!
Feel free to share the solution with Magento Community via social media.
Thank You.