Magento – Magento 2 check product attribute already exsists

magento2productproduct-attribute

I want to check if product attribute with same code already exists in setup file of my custom module?

How I could check it?

Best Answer

Try this:

Note: $eavSetupFactory should be an instance of  Magento\Eav\Setup\EavSetupFactory class, so add it to your constructor as a dependency.
/** @var Magento\Eav\Setup\EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

if(!$eavSetup->getAttributeId(\Magento\Catalog\Model\Product::ENTITY, 'attr_code')) {
    //Create the attribute
}

This will attempt to retrieve the attribute ID for the attribute with the code attr_code. If it returns a falsey value, the attribute does not exist.