Fetch Attribute Id from the attribute code in Magento 2 to using AttributeRepository Interface Class.
You need Entity type value and the attribute code.
Just instantiate the Magento\Eav\Api\AttributeRepositoryInterface class to retrieve the id value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php namespace Jesadiya\AttributeId\Model; use Magento\Catalog\Model\Product; use Magento\Eav\Api\AttributeRepositoryInterface; class GetAttribute implements DataPatchInterface { /** * @var AttributeRepositoryInterface */ private $attributeRepository; public function __construct( AttributeRepositoryInterface $attributeRepository ) { $this->attributeRepository = $attributeRepository; } public function getAttributeId() { $attribute = $this->attributeRepository->get(Product::ENTITY, 'sku'); return $$attribute->getAttributeId(); } } |
Here, We are fetching Product SKU attribute Id programmatically. You can pass any attribute value you want to retrieve it with entity type.
$getId = $this->getAttributeId();
The id will be the integer value of the attribute.
You can be interested to read Get Attribute id by product id Magento 2