Magento 2: How to check if product attribute exists or not?

Today our team had a requirement to check if product custom attribute exists or not. We wanted to make sure that we don’t try to create the same attribute again if it already exists.

After spending few hours we found the best way to do so and thought we should share this with our Magento 2 developers out there because we are confident this is going to help others as well.

Let’s crack on with the code to find out how to check if product attribute exists in Magento 2 or not

<?php class Custom
{ /** * @var MagentoEavModelConfig */ private $_eavConfig; /** * @param MagentoEavModelConfig $eavConfig */ public function __construct( MagentoEavModelConfig $eavConfig ) { $this->_eavConfig = $eavConfig; } /** * Returns true if attribute exists and false if it doesn't exist * * @param string $field * @return bool * @throws MagentoFrameworkExceptionLocalizedException */ public function isProductAttributeExists($field) { $attr = $this->_eavConfig->getAttribute(Product::ENTITY, $field); return ($attr && $attr->getId()); }
}

As you can see in the above code the getAttribute function of MagentoEavModelConfig class can help finding out if the product attribute exists or not.

That’s it, Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.