Use code MAG25 to get $25 off! Limited time offer on Cloudways Magento hosting.
AVAIL NOW

How to Override Model in Magento 2

A Model is an important part of MVC (Model-View-Controller) pattern as it represents the data of the application. In the same way, Models have a very useful role in Magento as well. Since editing Model from the core files is not a good practice, you should instead rewrite Model in Magento 2!

Hence, in this tutorial, I am going to teach you how to override models in Magento 2. What you need is a custom module to do that, so let’s begin.

Steps to Follow

  • Create Directories
  • Configuration of Module
  • Registration of Module
  • Override di.xml
  • Override Product.php
  • Launch SSH and Run Commands

Create Directories

In the root directory of your store, create the following directories in the same manner shown below:

directory model

Configuration of Module

Create module.xml in app/code/Magenticians/Moduleproduct/etc and add the following code in it:

Registration of Module

Create registration.php in app/code/Magenticians/Moduleproduct and add the following code in it:

Override di.xml

Create di.xml  in app/code/Magenticians/Moduleproduct/etc in order to specify which model to override by using <preference for=””>  and <preference type=””>.

Add the following code in it: The purpose of creating this file is to override di.xml file

<preference for=””> Which Model to override.

<preference type=””> Where to override.

Override Product.php

Now create Product.php in app/code/Magenticians/Moduleproduct/Model/Catalog and add the following code in i

In the code above, I have overriden the product name and product SKU.

Launch SSH and Run Commands

Run the following commands in the Magento 2 root directory:

Now it’s time to check results! Go to the product page and you should see this:

result override model

Conclusion

After the implementation of all the steps above, you should be able to override Model in Magento 2. You can override more Models with the same approach depending on your requirements. If you still have any confusion related to this tutorial, just leave a comment below!

About Author

Syed Muneeb Ul Hasan is an expert in PHP and Magento, he prefers to educate users in implementing and learning Magento. When not working, he loves to watch cricket.

  • Shiljith Mp

    I tried override model in magento 2.1.8 i got the output but the design is not working