Helllo All,

I want to retrieve attribute code and attribute details from attribute id. In magento1, I am doing it as:

$attrCode = Mage::getModel('eav/entity_attribute')->load($attributeId)->getAttributeCode();

How can we get this in magento 2.

Thanks in advance :)

3 Answers 3

    $eavModel = $this->_objectManager->create('Magento\Catalog\Model\ResourceModel\Eav\Attribute');
    $attr = $eavModel->load($attributeId);
    $attributeCode = $attr->getAttributeCode();//Get attribute code from its id
    echo $attributeCode;

     /*Get attribute details*/
    $attributeDetails = $this->eavConfig->getAttribute("catalog_product", $attributeCode);
  • 1
    You don't specify the source class for $this->eavConfig Aug 8, 2018 at 21:01
  • 1
    @domdambrogia you can follow here, its worked. magento.stackexchange.com/a/105171/70258
    – fudu
    Dec 29, 2018 at 7:41
  • where you are using $attr? Jan 16, 2019 at 12:34
  • How to fetch for multiple attribute code like color and size can I pass an array? Oct 10, 2019 at 14:35

You can also use Magento\Catalog\Api\ProductAttributeRepositoryInterface and inject it into your class.

You can use the "get" method of the repository class. This works for me even if I supplied an attribute_id instead of the attribute_code. I've tested it in 2.2.6.

class Items extends \Magento\Framework\View\Element\Template{
    protected $repository;
    public function __construct(
        \Magento\Catalog\Api\ProductAttributeRepositoryInterface $repository
        $this->repository = $repository;
    public function test($attributeId){
        $attribute = $this->repository->get($attributeId);
  • 1
    Thank you for giving the best answer that doesn't use the object manager. Feb 11, 2021 at 22:41

You can try with

  * Get attribute info by attribute code and entity type
$attributeCode = 'color';
$entityType = 'catalog_product';

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();

$attributeInfo = $objectManager->get(\Magento\Eav\Model\Entity\Attribute::class)
                               ->loadByCode($entityType, $attributeCode);

//var_dump($attributeInfo->getData()); exit;

 * Get all options name and value of the attribute
$attributeId = $attributeInfo->getAttributeId();
$attributeOptionAll = $objectManager->get(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class)

//var_dump($attributeOptionAll->getData()); exit;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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