16

How can I get a list of all available products in Magento 2?

2
  • My answer hasn't helped you? Sep 9, 2016 at 12:51
  • 1
    Mark now @SiarheyUchukhlebau answer as correct....
    – P0lT10n
    Mar 15, 2017 at 14:28

5 Answers 5

34

You should use Magento\Catalog\Model\ProductRepository or Magento\Catalog\Model\ResourceModel\Product\Collection according your needs. You can use both methods to get product instances with all data.

Example 1 (Repository):

/**
 * @param \Magento\Catalog\Model\ProductRepository $productRepository
 * @param \Magento\Framework\Api\SearchCriteriaInterface $criteria
 * @param \Magento\Framework\Api\Search\FilterGroup $filterGroup
 * @param \Magento\Framework\Api\FilterBuilder $filterBuilder
 * @param \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus
 * @param \Magento\Catalog\Model\Product\Visibility $productVisibility
 */
public function __construct(
    \Magento\Catalog\Model\ProductRepository $productRepository,
    \Magento\Framework\Api\SearchCriteriaInterface $criteria,
    \Magento\Framework\Api\Search\FilterGroup $filterGroup,
    \Magento\Framework\Api\FilterBuilder $filterBuilder,
    \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
    \Magento\Catalog\Model\Product\Visibility $productVisibility
) {
    $this->productRepository = $productRepository;
    $this->searchCriteria = $criteria;
    $this->filterGroup = $filterGroup;
    $this->filterBuilder = $filterBuilder;
    $this->productStatus = $productStatus;
    $this->productVisibility = $productVisibility;

    $this->getProductData();
}

/**
 * @return \Magento\Cms\Model\Block|null
 * @throws \Magento\Framework\Exception\NoSuchEntityException
 */
protected function getProductData()
{

    $this->filterGroup->setFilters([
        $this->filterBuilder
            ->setField('status')
            ->setConditionType('in')
            ->setValue($this->productStatus->getVisibleStatusIds())
            ->create(),
        $this->filterBuilder
            ->setField('visibility')
            ->setConditionType('in')
            ->setValue($this->productVisibility->getVisibleInSiteIds())
            ->create(),
    ]);

    $this->searchCriteria->setFilterGroups([$this->filterGroup]);
    $products = $this->productRepository->getList($this->searchCriteria);
    $productItems = $products->getItems();

    return $productItems;
}

Result:

repository

Example 2 (Collection):

/**
 * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
 * @param \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus
 * @param \Magento\Catalog\Model\Product\Visibility $productVisibility
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
    \Magento\Catalog\Model\Product\Visibility $productVisibility
) {
    $this->productCollectionFactory = $productCollectionFactory;
    $this->productStatus = $productStatus;
    $this->productVisibility = $productVisibility;
}

/**
 * @return \Magento\Framework\DataObject[]
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function getProducts()
{
    /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
    $collection = $this->productCollectionFactory->create();
    $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
    $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
    $collection->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
        ->addAttributeToFilter('visibility', ['in' => $this->productVisibility->getVisibleInSiteIds()]);

    return $collection->getItems();
}

Result:

collection

6
  • hi @siarhey, I am getting an empty result with your code. Do you have any tips about it? Could it be because of I am trying to retrieve the list from a cron task?
    – Lorenzo S
    Feb 10, 2017 at 11:22
  • @LorenzoS Hi, which example you are using 1 or 2? Does any product exist when you remove all filters/conditions? Feb 10, 2017 at 11:36
  • 1
    How do get this "Variables" tab with objects tree in your screenshot ?
    – DevonDahon
    May 15, 2017 at 7:12
  • 1
    @maxagaz Using xDebug in PHPStorm May 15, 2017 at 7:15
  • great answer, @SiarheyUchukhlebau but what do you mean by If you need just product data use the first class. If you need to get the product instances - use second class. May 31, 2017 at 18:57
8

The most upvoted answer is working but I would like to mention that here by injecting a product repository implementation directly will cause the breach of service contract principle & that is something Magento wants developers to correct. You should inject \Magento\Catalog\Api\ProductRepositoryInterface $productRepository instead of it's implementation which is \Magento\Catalog\Model\ProductRepository $productRepository. That way you you will have a space for future upgrade ability. Bottom line is use Service contracts as much as possible.

2

Using a REST API call:

https://{host}/rest/V1/products/?searchCriteria=

Retrieves all products. "searchCriteria" is a required param, but can be left blank, as above.

0

You can do this through api request. Take a look at the default m2 api

think your better shoot is catalogProductRepositoryV1

0
<?php

declare(strict_types=1);
namespace Moazzam\LatestProduct\Controller\Index;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Controller\Result\Json;
use Magento\Staging\Controller\Result\JsonFactory;

/**
 * Excute the list of products
 *
 * Class Index
 */
class Index implements HttpPostActionInterface, HttpGetActionInterface
{
    /**
     * @var ProductRepositoryInterface
     */
    protected ProductRepositoryInterface $productRepository;

    /**
     * @var SearchCriteriaBuilder
     */
    protected SearchCriteriaBuilder $searchCriteria;

    /**
     * @var FilterBuilder
     */
    protected FilterBuilder $filterBuilder;

    /**
     * @var JsonFactory
     */
    protected JsonFactory $jsonFactory;

    public function __construct(
        ProductRepositoryInterface $productRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        FilterBuilder $filterBuilder,
        JsonFactory $jsonFactory
    ) {
        $this->productRepository = $productRepository;
        $this->searchCriteria = $searchCriteriaBuilder;
        $this->filterBuilder=$filterBuilder;
        $this->jsonFactory=$jsonFactory;
    }

    /**
     *  Get the list of  products through search critarea
     *
     * @return Json
     */
    public function execute(): Json
    {
        $filters = $this->filterBuilder
            ->setField('name')
            ->setConditionType('like')
            ->setValue('%hoodie%')
            ->create();
        $searchCriteria = $this->searchCriteria->addFilter($filters)
            ->addSortOrder('created_at', 'DESC')
            ->setPageSize(20)
            ->setCurrentPage(1)
            ->create();
        $products = $this->productRepository->getList($searchCriteria)->getItems();
        foreach ($products as $product) {
            $getData[] = [
                'sku' => $product->getSku(),
                'name' => $product->getName()
            ];
        }
        return $this->jsonFactory->create()->setData($getData);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.