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 \Magento\Eav\Model\Config
     */
    private $_eavConfig;

    /**
     * @param \Magento\Eav\Model\Config $eavConfig
     */
    public function __construct(
        \Magento\Eav\Model\Config $eavConfig
    ) {
        $this->_eavConfig = $eavConfig;
    }

    /**
     * Returns true if attribute exists and false if it doesn't exist
     *
     * @param string $field
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    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 \Magento\Eav\Model\Config 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.

3 thoughts on “Magento 2: How to check if product attribute exists or not?

  1. Thanks for sharing.
    Just would like to add that once you did return ($attr && $attr->getId()), adding ? true : false is not necessary as it already will return true or false.

    i.e.:
    return ($attr && $attr->getId());

    will do the same thing

Leave a Reply

Your email address will not be published. Required fields are marked *