How To Create CRUD Model In Magento 2

CRUD Model in Magento 2 is one of the essential part of handling data in the database. CRUD means Create, Read, Update and Delete, you can write less code to create this functionality. This article will walk you through the main steps(Database, Model, Resource Model and Resource Magento 2 Get Collection and do database-related operations) to create a CRUD Model in Magento 2.

You may also know

Create Model in Magento 2

Follow the following steps to create CRUD Model in Magento 2

  • Create Database
  • Create Model
  • Create Resource Model
  • Create Resource Model Collection
  • Create Factory Object

Create Database

The db_schema.xml file in Magento 2 is a database schema definition file that is used to declare the database structure for a module. It is a part of the database layer in Magento 2 and provides information about the tables, columns, indexes, and foreign keys that a module requires in the database.



Code of db_schema.xml

<schema xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="gdblogger_demomodule_post ">
        <column xsi:type="int" name="post_id" padding="10" unsigned="true" nullable="false" identity="true" comment="Post ID"/>
        <column xsi:type="varchar" name="name" nullable="false" length="255" comment="Post Name"/>
        <column xsi:type="varchar" name="url_key" nullable="false" length="255" comment="Post URL Key"/>
        <column xsi:type="text" name="post_content" nullable="false" comment="Post Content"/>
        <column xsi:type="text" name="tags" nullable="false" comment="Post Tags"/>
        <column xsi:type="smallint" name="status" nullable="false" default="0" comment="Post Status"/>
        <column xsi:type="varchar" name="featured_image" nullable="false" length="255" comment="Post Featured Image"/>
        <column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Post Created At"/>
        <column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="CURRENT_TIMESTAMP" comment="Post Updated At"/>

        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="post_id"/>

Create Model

A Model in Magento 2 is a part of the Model-View-Controller (MVC) architecture of the platform and is used to represent the data and the business logic of a module. The Model layer is responsible for retrieving, saving, and manipulating the data in the database.



Code of Post.php

namespace GDBlogger\DemoModule\Model;
class Post extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface
	const CACHE_TAG = 'gdblogger_demomodule_post';

	protected $_cacheTag = 'gdblogger_demomodule_post';

	protected $_eventPrefix = 'gdblogger_demomodule_post';

	protected function _construct()

	public function getIdentities()
		return [self::CACHE_TAG . '_' . $this->getId()];

	public function getDefaultValues()
		$values = [];

		return $values;

The code creates the Post Magento 2 Model class. For a module called DemoModule in the GDBlogger namespace, the Model class represents the data and business logic.

The class implements the \Magento\Framework\DataObject\IdentityInterface interface and extends the \Magento\Framework\Model\AbstractModel class, which is used to supply cacheable data for Model objects.

The Model object’s cacheable data is identified by the constant CACHE_TAG, the class variables $_cacheTag and $_eventPrefix, and the Magento cache management system.

The Model class’s function Object() { [native code] }, the _construct() method, is used to initialise the Model object. The _init method is invoked by the method, which sets the Resource Model class that will be utilised by the Model class to perform database activities.

Cache tags linked to the Model object are returned in an array by the getIdentities() method. The Model object’s cacheable data is identified using this by the Magento cache management system.

The default values for a Model object are returned by the getDefaultValues() function. It can be used to provide default values for attributes on a new instance of the Model object.

Overall, the Magento 2 module’s business logic and data are represented in a structured manner by the Model class, which also offers methods for initialising, caching, and accessing the data for the Model object.

Create Resource Model

The Resource Model in Magento 2 is a component of the Model-View-Controller (MVC) architecture and handles database activities for a module. Data retrieval from the database as well as database-related actions like record creation, update, and deletion falls under the purview of the Resource Model layer.



Content of Post.php

namespace GDBlogger\DemoModule\Model\ResourceModel;

class Post extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
	public function __construct(
		\Magento\Framework\Model\ResourceModel\Db\Context $context
	protected function _construct()
		$this->_init(gdblogger_demomodule_post, 'post_id');

A class called Post in the Magento 2 Resource Model is defined by the code. The DemoModule module in the GDBlogger namespace contains the Resource Model class.

The class extends the foundation class for all Magento 2 Resource Model classes, the \Magento\Framework\Model\ResourceModel\DbAbstractDb class.

The constructor for the class takes a \Magento\Framework\Model\ResourceModel\Db\Context object as an argument and passes it to the parent class’s constructor. The Resource Model class uses the Context object to access the database connection and other necessary resources.

The Resource Model object is initialised using the _construct method, which is the constructor of the Resource Model class. It invokes the _init function to set the primary key and name of the database table that the Resource Model will utilise.

Overall, the Resource Model class provides a structure for performing database operations for the DemoModule module in Magento 2. The class performs database operations like creating, updating, and deleting records, and handles data retrieval operations. The Resource Model class provides a convenient way to interact with the database and manipulate the data stored in the database.

Create Resource Model Collection – Get Model Collection

A Model Collection in Magento 2 is a collection of model objects. Used to manage a group of related data records. The collection is used to perform operations on multiple records at once. Such as retrieving, updating, or deleting records from the database.



Code of Collection.php

namespace GDBlogger\DemoModule\Model\ResourceModel\Post;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
	protected $_idFieldName = 'post_id';
	protected $_eventPrefix = 'gdblogger_demomodule_post_collection';
	protected $_eventObject = 'post_collection';

	 * Define resource model
	 * @return void
	protected function _construct()
		$this->_init('GDBlogger\DemoModule\Model\Post', 'GDBlogger\DemoModule\Model\ResourceModel\Post');


This file is a Magento 2 Model Collection class for the GDBlogger\DemoModule\Model\Post model. It is used to manage a group of related data records for the Post model.

The Collection class extends the \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection class, which provides basic functionality for working with collections of model objects in Magento 2.

The property $_idFieldName specifies the name of the primary key field for the Post model.

Define the prefix and object for events with the $_eventPrefix and $_eventObject properties in the collection class.

The _construct() method defines the resource model for the collection class. The model class and resource model class are set for the collection using the $this-> init(‘GDBloggerDemoModuleModelPost’, ‘GDBloggerDemoModuleModelResourceModelPost’) method.

In summary, this Collection class provides a convenient way to manage a group of related Post model objects and is an important part of the Model-View-Controller (MVC) architecture in Magento 2.

Create Factory Object

In Magento 2, you use factory objects to programmatically create other objects. These objects come in handy for creating objects with complex dependencies or initialization requirements. They also centralize the logic for instantiating objects.

The factory object in Magento 2 typically follows the Factory Design Pattern, which is a creational pattern in software design. They have a common interface and delegate object instantiation to subclasses.

In Magento 2, factory objects create models, blocks, helpers, and other objects. They have the name convention [VendorName][ModuleName][Type][ClassName]Factory], where [Type] designates whether they are Model, Block, or Helper objects, and they are found in the Model, Block, and Helper directories of a module.

For instance, you would use the PostFactory class, which is defined in the GDBlogger\DemoModule\Model\PostFactory file, to generate an instance of the Post model in the GDBlogger\DemoModule module. The factory class, used in the controller classes and other parts of the module, provides a convenient way to create instances of the Post model.

Let’s call this file in Controller:

Code of Controller

namespace GDBlogger\DemoModule\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
	protected $_pageFactory;

	protected $_postFactory;

	public function __construct(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\View\Result\PageFactory $pageFactory,
		\GDBlogger\DemoModule\Model\PostFactory $postFactory
		$this->_pageFactory = $pageFactory;
		$this->_postFactory = $postFactory;
		return parent::__construct($context);

	public function execute()
		$post = $this->_postFactory->create();
		$collection = $post->getCollection();
		foreach($collection as $item){
			echo "<pre>";
			echo "</pre>";
		return $this->_pageFactory->create();

The file defines a Magento 2 controller class named Index which is part of the GDBlogger\DemoModule\Controller\Index namespace.

The controller uses a constructor to initialize two objects:

  • A \Magento\Framework\View\Result\PageFactory object, stored in the $_pageFactory property.
  • The \GDBlogger\DemoModule\Model\PostFactory object is stored in the $_postFactory property.

The execute() method of the controller retrieves a collection of Post objects using the PostFactory object. And prints the data for each item in the collection. The method returns a result page object created by the $_pageFactory object.

I hope this guide will be helpful to create CRUD Model in Magento 2. Please do not hesitate to contact us through the comments section if you have any further questions.

Leave a comment

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