Whats the best way to check if a custom attribute exists in Magento2

The question:

In being careful, I want to check if my custom attribute exists before I attempt to utilize it in any way. I need to check against all attributes collection, not just the product collection. My attribute may exist on a customer, a product, or on a custom model of my own creation.

In magento 1.x, I’d use the following:

$attr = Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter('specialty')->getFirstItem();

if ($attr->getAttributeId() > 0) {
 Do some stuff....'

I can’t find anything that explicitly does something like this

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You need use MagentoEavApiAttributeRepositoryInterface::get method for this.

For example:

try {

   $attribute = $this->attributeRepository->get($entityType, $attributeCode);

} catch (MagentoFrameworkExceptionNoSuchEntityException $e) {

    //  attribute does not exist

}

Method 2

You may also use MagentoCatalogApiProductAttributeRepositoryInterface to determine the product attribute

    try {
            $this->attributeRepository->get('custom_attribute');
        } catch (NoSuchEntityException $e) {

            //To-do create attribute
        }

This is verified on 2.3.2


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment