How to Fetch Data Using Collection in Magento 2

Learn how to retrieve data from the database using collections in Magento 2 with practical examples.

Overview

In Magento 2, collections are used to fetch multiple records from the database. They provide a flexible way to filter, sort, and manipulate data efficiently.

Step-by-Step Implementation

  1. Inject the required collection factory into your class.
  2. Create a collection instance.
  3. Apply filters, sorting, or limits if needed.
  4. Loop through the collection to get data.

Step 1: Inject Collection Factory


namespace Vendor\Module\Model;

use Vendor\Module\Model\ResourceModel\Item\CollectionFactory;

class GetData
{
    protected $collectionFactory;

    public function __construct(CollectionFactory $collectionFactory)
    {
        $this->collectionFactory = $collectionFactory;
    }
}
    

Step 2: Fetch Data from Collection


public function getItems()
{
    $collection = $this->collectionFactory->create();

    // Apply filters (optional)
    $collection->addFieldToFilter('status', 1);

    // Sorting (optional)
    $collection->setOrder('created_at', 'DESC');

    return $collection;
}
    

Step 3: Loop Through Collection


$items = $this->getItems();

foreach ($items as $item) {
    echo $item->getId();
    echo $item->getName();
}
    

Common Collection Methods

  • addFieldToFilter() – Add conditions
  • setOrder() – Sort data
  • setPageSize() – Limit records
  • setCurPage() – Pagination
  • getSize() – Total record count

Important Notes

  • Always use CollectionFactory instead of Object Manager.
  • Apply filters before loading large datasets to improve performance.
  • Use pagination for large collections.
  • Clear cache if needed: php bin/magento cache:flush