Magento 2 – Get all attributes of product
In this short tutorial I show you how to get all attributes of product. This is useful if you want to get a list of all available attributes for a specific product. I needed this, because of about 1000 product attributes and I wanted to automatically copy attributes from simple to configurable attributes. This can be done in one loop, if you know all attributes. But this it is necessary to not copy all (for example id, sku, …). So we can later adept the final list of attributes.
Magento 2 – Get all attributes of product
This small code example returns a list of all product attributes:
1 2 3 4 5 6 | $product = $this->_productRepository->get("PRODUCTSKU"); $attributes = $product->getAttributes(); foreach($attributes as $a) { echo $a->getName()."\n"; } |
You can get a collection of all attributes that are assigned to a product directly from its model. In a loop you can extract all needed data from it.
Product Repository
The code uses a new model from Magento 2 called product repository. From this repository you can get products by SKU like you can see, or by id. It provides the following two options:
- $this->_productRepository->get(‘sku’)
- $this->_productRepository->getById(‘id’)
If your sku or id is valid, you will get a product instance. If not you will get an error, so you may need to add a try catch block. You can get a product repository by injection. In you _construct method of your model you need to add:
1 2 3 4 5 6 7 | class MyModel { protected $_productRepository; public function __construct(\Magento\Catalog\Model\ProductRepository $productRepository) { $this->_productRepository = $productRepository; ... |
Product Repository Cache
For a import module we recognized a strange Magento 2 behavior. If you import many products with different attribute values you may notice wrong data. If an attribute has a null value and shouldn’t be set it is possible, that there is attribute data from another product. That happens if you get products by product repository in a loop. There is an internal Magento 2 product cache, so lazy loading only fills product attributes with data. If there are null data, you may get values from the previous product. To solve this, simply clear product repository cache before using it!
1 | $this->_productRepository->cleanCache(); |
Conclusion
You can get all attributes of product very easy. The use of product repository is a good idea if you know that there is an internal cache!