How to Apply Schema Patch in Magento 2?

How to Apply Schema Patch in Magento 2

Today I will be discussing How to Apply Schema Patch in Magento 2.

Schema patch is a class in Magento 2 that contains schema modification instructions so you can add, update, or delete columns in any custom table or EAV table.

Here, we are adding a new column in the existing table (“custom_table”) using schema patch.

Steps to Apply Schema Patch in Magento 2:

Step 1:  We need to create an “AddColumn.php” file inside our extension at the following path.

app\code\Vendor\Extension\Setup\Patch\Schema\

Then add the code as follows

<?php
namespace Vendor\Extension\Setup\Patch\Schema;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\Patch\SchemaPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class AddColumn implements SchemaPatchInterface
{
   private $moduleDataSetup;

   public function __construct(
       ModuleDataSetupInterface $moduleDataSetup
   ) {
       $this->moduleDataSetup = $moduleDataSetup;
   }

   public static function getDependencies()
   {
       return [];
   }

   public function getAliases()
   {
       return [];
   }

   public function apply()
   {
       $this->moduleDataSetup->startSetup();

       $this->moduleDataSetup->getConnection()->addColumn(
           $this->moduleDataSetup->getTable('custom_table'),
           'name',
           [
               'type' => Table::TYPE_TEXT,
               'length' => 255,
               'nullable' => true,
               'comment'  => 'Name',
           ]
       );

       $this->moduleDataSetup->endSetup();
   }
}

Step 2: After adding this file run the Magento upgrade command

php bin/magento setup:upgrade

Conclusion:

This way you can Apply Schema PAtch in Magento 2. Alternatively, learn How to Use Data Patch in Magento 2. In case you have any doubt let me know through the comment section. Stay in touch with us for more.

Happy Coding!

Previous Article

Magento 2 Extensions Digest March 2022 (New Release & Updates)

Next Article

How to Enable Phone Number Validation on the Customer Registration Page Magento 2?

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨