How to add a new column in admin_user table Magento 2 ?
2 Answers
app/code/vendor/modulename/Setup/UpgradeSchema.php
<?php
namespace Vendor\Module\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class UpgradeSchema implements UpgradeSchemaInterface
{
public function upgrade(SchemaSetupInterface $setup,
ModuleContextInterface $context){
$setup->startSetup();
if (version_compare($context->getVersion(), '1.0.1') < 0) {
// Get module table
$tableName = $setup->getTable('admin_user');
// Check if the table already exists
if ($setup->getConnection()->isTableExists($tableName) == true) {
// Declare data
$columns = [
'tok_value' => [
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'nullable' => true,
'comment' => 'Token Value',
],
];
$connection = $setup->getConnection();
foreach ($columns as $name => $definition) {
$connection->addColumn($tableName, $name, $definition);
}
}
}
$setup->endSetup();
}
}
Note: If you face any issue, it may be due to the module that you have already installed. As you know, if the module is already installed then setup:upgrade command does not install schema. You will need to look into your setup_module table, delete your module from the table and re-run the php bin/magento setup:upgrade command.
I'd like to answer the question: How to add new column in admin_user table? Now our Magento latest version is 2.4.7 . The recommended way to add new column in admin_user table is to use declarative schema
Ref: https://developer.adobe.com/commerce/php/development/components/declarative-schema/configuration/ In your custom extension, create file db_schema.xml
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="admin_user">
<column xsi:type="smallint" name="reminder_count" comment="Number of times sending password expire reminder email"/>
</table>
</schema>
Then you need to generate the file db_schema_whitelist.json By running this command:
php bin/magento setup:db-declaration:generate-whitelist --module-name=EXAMPLE_MODULE
Finally, you run this command
bin/magento set:up