How to update product attribute using Patch Data Magento 2?

Update Product attribute with Patch Data file in Magento 2.3 and above version.

Sometimes we have created a product attribute and want to change some of the fields after generating product attributes, you can do it easily with Magento.

Let’s take an example, We want to change product attributes of Open source sample data, Sale attribute title with Discount. Need to create a Setup folder in your module with the Patch\Data folder inside it and create any PHP file to update title.

<?php
namespace Jesadiya\SaleProduct\Setup\Patch\Data;

use Magento\Eav\Setup\EavSetup;
use Magento\Catalog\Model\Product;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class SaleAttribute implements DataPatchInterface
{
     /** @var ModuleDataSetupInterface */
    private $moduleDataSetup;

    /** @var EavSetupFactory */
    private $eavSetupFactory;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        EavSetupFactory $eavSetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $eavSetup->updateAttribute(
            Product::ENTITY,
            'sale',
            [
                'frontend_label' => 'Discount'
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
}

In the above code, We need to call, updateAttribute() method to update attribute.

The first parameter is an Entity type, we have a product entity type.

Second Parameter is the Product attribute code.

The third parameter takes an array, the column value to update attribute.

You can add multiple fields to update if you have or pass only the required field you want to change attribute value.

You must have to Run Command to see the updated value,
php bin/magento setup:upgrade

When you go to the admin panel and explore the Sale attribute, the Title will be changed to Discount.