Insert data while upgrading module (UpgradeData) – setup script – Magento 2

This is a continuation of the previous tutorial, It helps to insert data into the database while upgrading the module in Magento 2.

As per our previous tutorials, we summarize the below points

Now we insert data into the database while upgrading the module

When we use UpgradeData

Consider already you launch your module-version-1.0.0 into public marketplace, If you want to add more data into your upcoming version-1.0.1, then you should add logic in UpgradeData.

First change the module version in app/code/Bilal/Cruddemo/etc/module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="Bilal_Cruddemo" setup_version="1.0.1"/>

Create UpgradeData Script

namespace Bilal\Cruddemo\Setup;

use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class UpgradeData implements UpgradeDataInterface
    private $_cruddemoFactory;

    public function __construct(\Bilal\Cruddemo\Model\CruddemoFactory $cruddemoFactory)
        $this->_cruddemoFactory = $cruddemoFactory;

    public function upgrade( ModuleDataSetupInterface $setup, ModuleContextInterface $context ) {
        if (version_compare($context->getVersion(), '1.0.0') < 0) {
            $data = [
                'name' => 'Vignesh',
                'age' => '26',
                'designation' => 'software programer'


If you keenly observe the UpgradeSchema script, you can find the logic of version comparison.

if (version_compare($context->getVersion(), '1.0.1') < 0) {

As we discussed UpgradeSchema.php execute while running setup:upgrade so run the below command in your Magento root

php bin/magento setup:upgrade

If you check your table, you can found our new data.

About Bilal

I'm a software programmer, I handle Magento2 modifications at any level.

View all posts by Bilal →

Leave a Reply

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