Magento 2, provides a great feature of Uninstalling the module as well as the data installed during the process of module installation. As we can create tables and attributes with InstallData and InstallSchema, we can also remove tables as well as attributes with Magento’s Uninstaller script.
Note: Uninstaller at present only works for the module downloaded with composer. Also, Uninstaller script works fine on Magento v2.2.0, earlier versions were having issues during module uninstallation. For later versions, say, Magento v2.4.*, we can directly Uninstall a module with uninstall command and remove the data and the tables using Uninstall.php used in Setup/Patch/Data. Please check our Webkul Uninstall Module Attributes blog for a better picture of how to remove installed data and tables from the database.
First, we will install a TEST module using composer and then we will Uninstall it to check it is working.
To install the sample module you need to include this module in your composer.json file. In composer.json file in require section add the following code.
Now, in repositories section in composer.json file add the following code.
Magento 2 Company ? Find out More
"type": "vcs", "url": "https://gitlab.com/ayazwebkul/Webkul_UninstallerTest.git"
After adding the entry in composer.json, run the following command
php bin/magento composer install
Now, your module is installed in vendor directory. Composer install just download the code from git.
Now, you need to open the file Setup/Patch/Data/Uninstall.php and update the code according to the data you want to remove/delete permanently. After this, you need to run php bin/magento setup:upgrade for uninstallation of the data.
In the module, we have created a table wk_test. Now, when we will run php bin/magento setup:upgrade and Uninstaller command all the data and the table along with the module will be removed.
For Uninstalling the module, we need to run
php bin/magento module:uninstall Webkul_UninstallerTest
On successful Uninstall you will get the following message:
Removing data of Webkul_UninstallerTest Removing Webkul_UninstallerTest from module registry in database Removing Webkul_UninstallerTest from module list in deployment configuration Removing code from Magento codebase: Cache cleared successfully. Generated classes cleared successfully. Please run the 'setup:di:compile' command to generate classes. Info: Some modules might require static view files to be cleared. To do this, run 'module:uninstall' with the --clear-static-content option to clear them. Disabling maintenance mode
Now, if you will check the database table wk_test created during module installation is removed. For more information regarding Uninstaller you can refer to Magento Doc.
That’s all for this post, will be back with Uninstaller script removing the created attributes. If you have any query, please comment below.