In Magento 2, CRUD operations are essential for creating, reading, updating, and deleting records in the database. Whether you’re developing a custom module or working on an extension, understanding how to implement CRUD operations is fundamental. In this guide, we’ll walk you through the process of creating a simple CRUD model for managing custom data in your Magento 2 store.
Step 1: Create a Custom Module
Before creating a CRUD model, we first need to create a custom module in Magento 2. Let’s call our module Mavenbird_CrudExample. To begin:
- Navigate to the app/code directory in your Magento 2 installation.
- Create a directory structure:
app/code/Mavenbird/CrudExample.
Inside this folder, create the following files:
app/code/Mavenbird/CrudExample/registration.php
app/code/Mavenbird/CrudExample/etc/module.xml
The registration.php file registers the module with Magento:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Mavenbird_CrudExample',
__DIR__
);
And the module.xml file contains the module’s configuration:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Mavenbird_CrudExample" setup_version="1.0.0" />
Once these files are in place, the module is registered. Next, we can proceed with creating the CRUD model.
Step 2: Create the Model
Now that the module is set up, we’ll create the model that will handle the data. For our example, let’s say we’re managing "items" in the system.
Create the model file Item.php in the app/code/Mavenbird/CrudExample/Model directory:
<?php
namespace Mavenbird\CrudExample\Model;
use Magento\Framework\Model\AbstractModel;
use Mavenbird\CrudExample\Model\ResourceModel\Item as ResourceModel;
class Item extends AbstractModel
{
protected $_idFieldName = 'item_id'; // Primary key field
protected $_name = 'name'; // Field name for the item name
protected $_resourceModel = ResourceModel::class; // Reference to the resource model
// Constructor method to initialize resource model
protected function _construct()
{
$this->_init(\Mavenbird\CrudExample\Model\ResourceModel\Item::class);
}
// Getter method for item ID
public function getId()
{
return $this->_getData($this->_idFieldName);
}
// Getter method for item name
public function getName()
{
return $this->_getData($this->_name);
}
// Setter method for item name
public function setName($name)
{
return $this->setData($this->_name, $name);
}
}
This model defines two fields: item_id and name. We’re using Magento's AbstractModel as the base class, which provides methods for working with the database.
Step 3: Create the Resource Model
The resource model defines how the model interacts with the database table. Create the file Item.php in the app/code/Mavenbird/CrudExample/Model/ResourceModel directory:
<?php
namespace Mavenbird\CrudExample\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Item extends AbstractDb
{
// Initialize resource model with table name and primary key
protected function _construct()
{
$this->_init('mavenbird_crudexample_item', 'item_id'); // Table name and primary key
}
}
In this resource model, the table name is mavenbird_crudexample_item (this table will need to exist in your database), and the primary key is item_id.
Step 4: Create the Collection Model
The collection model allows us to retrieve multiple records from the database. It extends the AbstractCollection class. Create the file Collection.php in the app/code/Mavenbird/CrudExample/Model/ResourceModel/Item directory:
<?php
namespace Mavenbird\CrudExample\Model\ResourceModel\Item\Collection;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Mavenbird\CrudExample\Model\Item as Model;
use Mavenbird\CrudExample\Model\ResourceModel\Item as ResourceModel;
class Collection extends AbstractCollection
{
// Define collection’s field names
protected $_idFieldName = 'item_id';
protected $_nameFieldName = 'name';
protected $_itemClass = Model::class;
protected $_resourceModel = ResourceModel::class;
// Constructor method to initialize collection
protected function _construct()
{
$this->_init(Model::class, ResourceModel::class);
}
}
The collection model allows you to fetch all items from the database and is crucial for operations like retrieving lists of records.
Step 5: Create the Controller
To demonstrate the CRUD operations, let’s create a simple controller that fetches and displays all items. Create a file Index.php inside app/code/Mavenbird/CrudExample/Controller/Index:
<?php
namespace Mavenbird\CrudExample\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Mavenbird\CrudExample\Model\ResourceModel\Item\CollectionFactory;
class Index extends Action
{
protected $collectionFactory;
public function __construct(Context $context, CollectionFactory $collectionFactory)
{
parent::__construct($context);
$this->collectionFactory = $collectionFactory;
}
// Fetch all items and display their names
public function execute()
{
$collection = $this->collectionFactory->create();
foreach ($collection as $item) {
echo $item->getName(); // Display the name of each item
}
}
}
This controller fetches all items using the collection model and displays their names on the page. You can extend this functionality to handle Create, Update, and Delete actions as needed.
Step 6: Enable the Module
Once the code is in place, enable the module by running the following commands from the Magento root directory:
php bin/magento module:enable Mavenbird_CrudExample
php bin/magento setup:upgrade
php bin/magento cache:flush
After running these commands, your custom module is ready to use. You can test the controller by accessing http://your-magento-site.com/crudexample/index/index to see the list of items.
Conclusion
Creating CRUD models in Magento 2 is a critical skill for building custom modules. By following this guide, you’ve learned how to create models, resource models, collections, and controllers to manage data in your Magento store. At Mavenbird, we focus on making Magento development easier and more efficient. With a solid understanding of CRUD operations, you can extend your Magento store with custom functionalities and integrations. Happy coding!