How to Get Attribute Code using Attribute Id in Magento 2

Method 1 (Construct Method):

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

class Helloworld extends \Magento\Framework\View\Element\Template
{
    /**
     * \Magento\Eav\Model\Entity\Attribute
     */
    protected $attribute;

    /**
     * @param  \Magento\Framework\View\Element\Template\Context $context
     * @param  \Magento\Eav\Model\Entity\Attribute              $attribute
     * @param  array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Eav\Model\Entity\Attribute $attribute,
        array $data = []
    ) {
        $this->attribute = $attribute;
        parent::__construct($context, $data);
    }

    public function getCustomAttributeCode()
    {
        $attribute = $this->attribute->load(93); // pass attribute id here
        return $attribute->getAttributeCode();
    }
}
?>

Method 2 (Object Manager):

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$attribute = $objectManager->get(\Magento\Eav\Model\Entity\Attribute::class)->load(93); // pass attribute id here
echo $attribute->getAttributeCode();

Leave a comment

Your email address will not be published. Required fields are marked *