Magento2 How to add customer attribute


Magento 2.3 introduces the new way to modify data using Data and schema patches.
To add customer attribute we will implement \Magento\Framework\Setup\Patch\DataPatchInterface.
Create a class CustomerCustomAttributePatcher in your module Setup directory: Vendor\Module\Setup\Patch\Data\CustomerCustomAttributePatcher
<?php
namespace Vendor\Module\Setup\Patch\Data;
use Magento\Eav\Model\Config;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
class CustomerCustomAttributePatcher implements DataPatchInterface
{
/**
* @var Config
*/
private Config $eavConfig;
/**
* @var EavSetupFactory
*/
private EavSetupFactory $eavSetupFactory;
/**
* @var AttributeSetFactory
*/
private AttributeSetFactory $attributeSetFactory;
/**
* @param Config $eavConfig
* @param EavSetupFactory $eavSetupFactory
* @param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
Config $eavConfig,
EavSetupFactory $eavSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->eavConfig = $eavConfig;
$this->eavSetupFactory = $eavSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
public function apply()
{
$eavSetup = $this->eavSetupFactory->create();
$customerEntity = $this->eavConfig->getEntityType(\Magento\Customer\Model\Customer::ENTITY);
$attributesetId = $customerEntity->getDefaultAttributeSetId();
$attributeset = $this->attributeSetFactory->create();
$attributeGroupId = $attributeset->getDefaultGroupId($attributesetId);
$eavSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom_attr', [
'type' => 'int',
'input' => 'text',
'label' => 'Customer custom Attribute',
'required' => false,
'default' => 0,
'visible' => false,
'user_defined' => true,
'system' => false,
'is_visible_in_grid' => true,
'is_used_in_grid' => true,
'is_filterable_in_grid' => true,
'is_searchable_in_grid' => true,
'position' => 50,
'sort_order' => 50,
'note' => 'Customer custom Attribute'
]);
$customerAttribute = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom_attr');
$customerAttribute->addData([
'attribute_set_id' => $attributesetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer', 'customer_account_edit']
]);
$customerAttribute->save();
}
public static function getDependencies()
{
return [];
}
public function getAliases()
{
return [];
}
}
For multiple patches or adding multiple attributes:
- All classes must be under same Setup\Patch\Data directory.
- Must implement Magento\Framework\Setup\Patch\DataPatchInterface interface.






