Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a


👋 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.