🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Create Model File to Perform CRUD Operation in Magento 2

By Jignesh ParmarUpdated on Mar 17, 2025 2 min read

In the previous tutorial, you came to know how to create a table in Magento 2. This tutorial is all about creating a model file to perform CRUD operation.

To use a table in Magento, one has to create files for the model.

Bookmark this tutorial while developing a Magento 2 module.

Steps to Create Model File to Perform CRUD Operation in Magento 2:

Create a file having a name Extension.php in given address: app\code\Meetanshi\Extension\Model

The name of the table is Extension here so we have given the name of a file Extension.php.

For fetching and loading the data, you need to create another file “Extension.php” on a given location.

<?php
namespace Meetanshi\Extension\Model;

use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Extension extends AbstractModel
{
    protected function _construct()
    {
        $this->_init('Meetanshi\Extension\Model\ResourceModel\Extension');
    }
}

Create file app\code\Meetanshi\Extension\Model\ResourceModel\Extension.php

<?php
namespace Meetanshi\Extension\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Extension extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('extension', 'id');
    }
}

Another important file is Collection.php

Collection.php file helps to collect all the data of the table.

In the given path, create a file and copy the code.

app\code\Extension\Model\ResourceModel\Extension\Collection.php

<?php
namespace Meetanshi\Extension\Model\ResourceModel\Extension;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    protected function _construct()
    {
        $this->_init('Meetanshi\Extension\Model\Extension', 'Meetanshi\Extension\Model\ResourceModel\Extension');
    }
}

Done!

Note, For instance, you need to send data from other platforms’ registration forms to the Magento database or integrate API in mobile. For such requirements, we have to call an API that sends a request to the server. In such scenarios, use the code to perform CRUD operation using API in Magento 2!

I would be happy to answer your questions regarding this blog.

Please do consider sharing this blog with interested ones via social media.

Thanks a bunch.

Jignesh Parmar Full Image
Article byJignesh Parmar

An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.