Question

I am adding products programmatically in Magento 2. I want to recover all the manufacturers and test if it exists otherwise I want to create it.

How to recover all brands in magento2?

Was it helpful?

Solution

The manufacturer is a regular Magento EAV attribute of product entity. You can take all available values and labels using the following code snippet:

$om = \Magento\Framework\App\ObjectManager::getInstance();

/** @var \Magento\Catalog\Api\Data\ProductAttributeInterface $attribute */
$attribute = $om->get(\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class)
    ->get('manufacturer');

foreach ($attribute->getOptions() as $option) {
     var_dump($option->getValue() . ' -> ' . $option->getLabel());
}

You can use the same repository class to save the modified attribute. Please use constructor dependency injection instead of a direct call to object manager in your code.

Also, you can do the same using WebApi:

<route url="/V1/products/attributes/:attributeCode" method="GET">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="get"/>
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
<route url="/V1/products/attributes" method="GET">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="getList" />
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
<route url="/V1/products/attributes" method="POST">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="save"/>
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
<route url="/V1/products/attributes/:attributeCode" method="PUT">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="save"/>
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
<route url="/V1/products/attributes/:attributeCode" method="DELETE">
    <service class="Magento\Catalog\Api\ProductAttributeRepositoryInterface" method="deleteById"/>
    <resources>
        <resource ref="Magento_Catalog::attributes_attributes" />
    </resources>
</route>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top