Insert data while instaling module (InstallData) – setup script – Magento 2

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

As per our previous tutorial, we summarize the below points

Now we use the same CRUD object to insert data into our custom table.

  • InstallData.php script also executed while run “bin/magento setup:upgrade” , we use this features to insert data into our custom table.

Create InstallData Script

Create app/code/Vendor/Module/Setup/InstallData.php

namespace Bilal\Cruddemo\Setup;

use Magento\Framework\Module\Setup\Migration;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
    private $_cruddemoFactory;

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

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        $data = [
            'name' => 'Dinesh',
            'age' => '26'



As we discussed InstallData.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, not found our new data. What is happening?

setup:upgrade command directly check into setup_module table for the entry Bilal_Cruddemo (Vendor_Module)

  • If it is found, it skips execution of install script
  • If it is not found, it executes  InstallData

For the confirmation, run the below query to delete the table and remove our module entry from the setup_module table.

DROP TABLE `crud_test_emp1`
DELETE FROM `setup_module` WHERE `module`='Bilal_Cruddemo';

Now run the below commands

php bin/magento setup:upgrade

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

I hope it helps! Please carry the same source code to follow next tutorial.

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 *