How to Create Product Attribute in Magento 2 Programmatically?

Product attributes are characteristics of a product that help you offer customers a wide range of options and influence their purchasing decisions. Once you add product attributes in Magento, it doesn't end there. You can also use product attributes to define dynamic category rules, cart price rules, related product rules, and multiple other options. 

That being said, it is important for you to know how to create product attributes in Magento programmatically. Just in case you'll need to create multiple attributes faster.

To create product attributes in Magento programmatically create the InstallData.php file in the app/code/Vendor/Module/Setup/InstallData.php.

namespace Vendor\Module\Setup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
    private $eavSetupFactory;
    public function __construct(EavSetupFactory $eavSetupFactory)
$this->eavSetupFactory = $eavSetupFactory;
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
'type' => 'text',
'backend' => '',
'frontend' => '',
'label' => 'Sample Attribute',
'input' => 'text',
'class' => '',
'source' => '',
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => true,
'required' => true,
'user_defined' => false,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => ''

Once you finish, don't forget to run the following commands to install the module and that's it:

php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy

Note: if you don't want your website to be down during deployment, try these zero downtime deployment commands for Magento 2.

Then check your product attribute in the admin panel.

Create product attribute in Magento 2 programatically

If you want to remove the product attribute use the removeAttribute instead of addAttribute. Alternatively, instead of removing attributes you can update product attributes in bulk.

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);