I have the attribute code, But how do I check whether the attribute is exist in the attribute set or not. Please provide me a solution how to get the attribute id from attribute code in magento 2

4 Answers 4


Get Attribute Id By Attribute Code In Magento2.

Just you have to follow some steps.

Create constructor

 * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute
protected $_eavAttribute;
 * @param   Context                                           $context
 * @param   \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute
public function __construct(
    Context $context,
    \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute
    $this->_eavAttribute = $eavAttribute;

//Call the getIdByCode method of Attribute in any method.

//Your $this->_eavAttribute->getIdByCode('entity_type', 'attribute_code');

$attributeId = $this->_eavAttribute->getIdByCode('customer', 'company_name');

Also you can check more details here.

  • Can you tell me , What i have to replace in the place of customer and company_name
    – Jaisa
    May 22, 2018 at 6:28
  • Fatal Error: 'Uncaught ArgumentCountError: Too few arguments to function Magento\\Eav\\Model\\ResourceModel\\Entity\\Attribute::getIdByCode(),
    – Jaisa
    May 22, 2018 at 6:35
  • It shows error like above
    – Jaisa
    May 22, 2018 at 6:35
  • @Sri use your ->getIdByCode('entity_type', 'attribute_code'); May 22, 2018 at 6:36
  • 1
    thanks , I have tried like this $attributeId = $this->_eavAttribute->getIdByCode(\Magento\Catalog\Model\Product::ENTITY,'color');
    – Jaisa
    May 22, 2018 at 6:38

You can also use a product attribute repository class to do this:

public function __construct(
    \Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepository,
) {
    $this->productAttributeRepository = $productAttributeRepository;

public function example()

    $attribute = $this->productAttributeRepository->get('size');
    $sizeId = $attribute->getAttributeId();

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$entityAttribute = $objectManager->get('Magento\Eav\Model\ResourceModel\Entity\Attribute');
$attributeId = $entityAttribute->getIdByCode('ENTITY TYPE', 'ATTRIBUTE CODE');

for example, get the product attribute ID with the attribute code brand:

$attributeId = $entityAttribute->getIdByCode('catalog_product', 'brand');

Try this one- https://webkul.com/blog/get-attribute-id-attribute-code-magento2/

You can also see how we can get customer and company name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.