Magento2 How to get custom attribute and its value of a customer?

The question:

I followed this tutorial to add a custom attribute to Customer. Then in Controller LoginPost.php, I want to get the value of that attribute of a particular customer to do some checking. But I found it completely different from Magento 1.X to retrieve the value of a custom attribute.

Anyone can suggest some methods? Thanks.

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

MagentoCustomerApiDataCustomerInterface extends MagentoFrameworkApiCustomAttributesDataInterface that have getCustomAttribute() method. You can use it to get custom attribute.
ex. for test:

$customerRepository = $objectManager
        ->get('MagentoCustomerApiCustomerRepositoryInterface');
$customer = $customerRepository->getById(1);
$cattrValue = $customer->getCustomAttribute('my_custom_attribute');


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