Get all admin users as an array in Magento 2
Today, while working with a project which happens to be bulit on top of Magento 2, I needed to find a way to get the list all the admin users as an array.
The obvious way to achieve this in Magento 2 is to use the \Magento\User\Model\ResourceModel\User\Collection
collection using following code.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$adminUsers = $objectManager->get('\Magento\User\Model\ResourceModel\User\Collection')->toOptionArray();
But upon debugging, I’ve found that the method toOptionArray()
is not implemented in this particular collection natively and so I’m left with an array with empty value and label in it.
To overcome this issue, I’ve tried another approach. In this, I’ve injected \Magento\User\Model\ResourceModel\User\CollectionFactory
into the constructor like below.
public function __construct(
...
\Magento\User\Model\ResourceModel\User\CollectionFactory $userCollectionFactory
)
{
$this->userCollectionFactory = $userCollectionFactory;
}
And then created the following method which returns an array of admin users,
private function getAdminUsers()
{
$adminUsers = [];
foreach ($this->userCollectionFactory->create() as $user) {
$adminUsers[] = [
'value' => $user->getId(),
'label' => $user->getName()
];
}
return $adminUsers;
}
Here, Calling the create() method on $this->userCollectionFactory
factory gives you an instance of its specific class and in turn returns the admin users.
One thing to note here is, When you reference a factory in a class constructor, Magento’s object manager generates the factory class if it does not exist. So, in order to see above code in action I needed to use following command which will re-generate classes factories:
$ php bin/magento s:d:c
And that is how I’ve solved this specific issue.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.