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

How I could check it?


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.

  • 1
    $setup means what ? – Jaisa May 22 '18 at 6:11
// use Magento\Eav\Api\AttributeRepositoryInterface;

     * Installs data for a module
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface   $context
     * @return void
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        if (version_compare($context->getVersion(), '1.0.0', '<')) {
            try {
            } catch (NoSuchEntityException $e) {
                        'type'                    => 'varchar',
                        'input'                   => 'textarea',
                        'label'                   => 'Special Measure Message',
                        'required'                => false,
                        'group'                   => 'General',
                        'global'                  => ScopedAttributeInterface::SCOPE_GLOBAL,
                        'is_used_in_grid'         => true,
                        'user_defined'            => false,
                        'visible'                 => true,
                        'used_in_product_listing' => true,

since \Magento\Framework\Setup\ModuleDataSetupInterface $setup does not contain a getAttributeId() method you always need to call the attributeRepository to get the attribute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.