Fetch Attribute Id from the attribute code in Magento 2 by using AttributeRepository Interface Class.
You need the Entity type value and the attribute code.
Just instantiate the Magento\Eav\Api\AttributeRepositoryInterface class to retrieve the id value.
<?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 with the 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