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
- Inject the required collection factory into your class.
- Create a collection instance.
- Apply filters, sorting, or limits if needed.
- 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 conditionssetOrder()– Sort datasetPageSize()– Limit recordssetCurPage()– PaginationgetSize()– 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