Back to Top

Get Administrators Role’s User Ids programmatically in Magento 2

Updated 18 June 2024

Hello Friends!!!
In this article, we will learn how we can get all user ids of the ‘Administrators‘ user role in Magento 2.

Here, to get the user Ids, I have created a method getAdminUserIds in the following Helper class file.
You can add this method to your required class file and can call on the required places in your code.

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomModule
 * @author    Webkul Software Private Limited
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Webkul\CustomModule\Helper;

use Magento\User\Model\ResourceModel\User\CollectionFactory as UserCollectionFactory;

/**
 * Webkul CustomModule Helper Data.
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * const ADMIN_ROLE
     */
    private const ADMIN_ROLE = "Administrators";

    /**
     * @var UserCollectionFactory
     */
    private $userCollFactory;

    /**
     * Constructor
     *
     * @param UserCollectionFactory $userCollFactory
     * @param \Magento\Framework\App\Helper\Context $context
     * @return void
     */
    public function __construct(
        UserCollectionFactory $userCollFactory,
        \Magento\Framework\App\Helper\Context $context
    ) {
        $this->userCollFactory = $userCollFactory;
        
        parent::__construct($context);
    }

    /**
     * Get Administrator Role's user ids
     *
     * @return array
     */
    public function getAdminUserIds()
    {
        $ids = [];
        try {
            $userColl = $this->userCollFactory->create()
                ->addFieldToSelect("user_id");
           
            $userColl->getSelect()
                ->where("`detail_role`.`role_name` = '".(self::ADMIN_ROLE).
                "' AND user_role.parent_id=detail_role.role_id");

            $userIdsColl = (!empty($userColl))?$userColl->getData():[];

            foreach ($userIdsColl as $each) {
                $ids[] = $each["user_id"] ?? 0;
            }
        } catch (\Exception $e) {
            //to do here
        }
        return $ids;
    }
}

Hope this will be helpful.
Thanks 🙂

Searching for an experienced
Magento Company ?
Find out More
. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home