How to Get Attribute ID by Attribute Code in Magento 2

attribute-setmagento2.2.2product-attribute

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

Best Answer

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;
    parent::__construct($context);
}

//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.