A role belongs to many users.

@return BelongsToMany
558946
public function administrators() : BelongsToMany
    {
        $pivotTable = config('admin.database.role_users_table');

        $relatedModel = config('admin.database.users_model');

        return $this->belongsToMany($relatedModel, $pivotTable, 'role_id', 'user_id');
    }
947531
private function belongsToMany()
    {
        // Return if there are no relationships of that type
        if (!isset($this->relationships['belongsToMany']) || empty($this->relationships['belongsToMany'])) {
            return $this;
        }

        // Group by primary key
        $this->db()->groupBy($this->table . '.' . $this->primaryKey);

        // Iterate relationships
        foreach ($this->relationships['belongsToMany'] as $join) {

            // Perform join
            $this->db()->join($join['pivot'], $this->primaryKey, '=', $join['localKey']);

            // Add related columns to select
            $column = 'GROUP_CONCAT(' . $join['pivot'] . '.' . $join['foreignKey'] . ') as concat_' . $join['alias'];
            $this->db()->addSelect($column);
        }

        // Return model instance
        return $this;
    }
606971
public function getRole() {

		$roleTable			= CoreTables::getTableName( CoreTables::TABLE_ROLE );
		$siteTable			= CoreTables::getTableName( CoreTables::TABLE_SITE );
		$siteMemberTable	= CoreTables::getTableName( CoreTables::TABLE_SITE_MEMBER );

		// TODO: Check why it's not working without appending one() after recent Yii Upgrade
		return Role::find()
			->leftJoin( $siteMemberTable, "$siteMemberTable.roleId = $roleTable.id" )
			->leftJoin( $siteTable, "$siteTable.id = $siteMemberTable.siteId" )
			->where( "$siteMemberTable.userId=:id AND $siteTable.slug=:slug", [ ':id' => $this->id, ':slug' => Yii::$app->core->getSiteSlug() ] )
			->one();
	}
273755
public function getRole()
	{
		if ($this->_user === NULL) {
			$this->_initUser();
		}

		if ($this->_user->getRole()) {
			return $this->_user->getRole();
		}

		return Acl::DEFAULT_ROLE;
	}
716504
public function getRoles()
    {
        $roles = parent::getRoles();

        foreach ($this->getUserRoles() as $userRole) {
            /* @var UserRole $userRole */
            $roles[] = $userRole->getRole()->getIdentifier();
        }

        return $roles;
    }
770117
public function getRoles()
    {
        $this_roles = \Cache::remember(
            'acl.getRolesById_'.$this->id,
            config('acl.cacheMinutes'),
            function () {
                return $this->roles;
            }
        );

        $slugs = method_exists($this_roles, 'pluck') ? $this_roles->pluck('slug','id') : $this_roles->lists('slug','id');
        return is_null($this_roles)
            ? []
            : $this->collectionAsArray($slugs);
    }
148294
public function permissions()
    {
        $permissions = $this->morphToMany(
            Config::get('laratrust.models.permission'),
            'user',
            Config::get('laratrust.tables.permission_user'),
            Config::get('laratrust.foreign_keys.user'),
            Config::get('laratrust.foreign_keys.permission')
        );

        if (Config::get('laratrust.use_teams')) {
            $permissions->withPivot(Config::get('laratrust.foreign_keys.team'));
        }

        return $permissions;
    }
64623
public function user()
    {
        $user = parent::user();

        // Load roles if user is set first time
        if ($user !== null && ($this->roles === null || $this->permissions === null)) {
            $this->groups      = [];
            $this->roles       = [];
            $this->permissions = [];

            // Load roles only if User model is permission based user
            if ($user instanceof User) {
                $this->addGroups($user->groups);
                $this->addRoles($user->roles);
                $this->addPermissions($user->permissions);

                $this->roles       = array_unique($this->roles);
                $this->permissions = array_unique($this->permissions);
            }
        }

        return $user;
    }
593681
public function getRoles()
    {
        return (!$this->roles) ? $this->roles = $this->roles()->get() : $this->roles;
    }
268945
public function belongsToMany(string $related, ?string $primary_key = null, ?string $foreign_key = null)
    {
        $relatedModel = app()->make($related);
        $local_key = $local_key ?? $this->getKey();
        // Make the table name singular and append ID to it
        // FIXME: Use a more reliable approach
        $foreign_key = $foreign_key ?? rtrim($relatedModel->getTable(), 's').'_id';
        return new BelongsToMany($relatedModel, $this, $primary_key, $foreign_key);
    }
957884
protected function getRoleSets()
    {
        return Util::getRoleSets($this->getUsername(), new String($this->lookupName), new String($this->rolesQuery), $this);
    }
1217462
public function rolePermissions()
    {

        $permissions = new Collection();
        foreach ($this->getRoles() as $role)
            $permissions = $permissions->merge($role->permissions);
        return $permissions;
    }
763510
protected function _roles()
    {
        $this->loadModel('CakeManager.Roles');

        $list = $this->Roles->find('list')->toArray();

        if (empty($list)) {
            $this->out('No roles found.');
        }

        // Creating administrators
        if (!in_array('Administrators', $list)) {
            $data = [
                'name' => 'Administrators',
                'login_redirect' => '/admin/manager/pages/dashboard',
            ];

            $new = $this->Roles->newEntity($data);
            if ($this->Roles->save($new)) {
                $this->out('Role "Administrators" created');
            } else {
                $this->out('Role "Administrators" could not be created');
                return false;
            }
        }

        // Creating moderators
        if (!in_array('Moderators', $list)) {
            $data = [
                'name' => 'Moderators',
                'login_redirect' => '/',
            ];

            $new = $this->Roles->newEntity($data);
            if ($this->Roles->save($new)) {
                $this->out('Role "Moderators" created');
            } else {
                $this->out('Role "Moderators" could not be created');
                return false;
            }
        }

        // Creating Users
        if (!in_array('Users', $list)) {
            $data = [
                'name' => 'Users',
                'login_redirect' => '/',
            ];

            $new = $this->Roles->newEntity($data);
            if ($this->Roles->save($new)) {
                $this->out('Role "Users" created');
            } else {
                $this->out('Role "Users" could not be created');
                return false;
            }
        }

        // Creating unregisterd
        if (!in_array('Users', $list)) {
            $data = [
                'name' => 'Unregistered',
                'login_redirect' => '/',
            ];

            $new = $this->Roles->newEntity($data);
            if ($this->Roles->save($new)) {
                $this->out('Role "Unregistered" created');
            } else {
                $this->out('Role "Unregistered" could not be created');
                return false;
            }
        }

        $this->out("Done.");
        return true;
    }
956988
public function users()
    {
        $relation = $this->morphedByMany(
            Models::classname(User::class),
            'entity',
            Models::table('assigned_roles')
        )->withPivot('scope');

        return Models::scope()->applyToRelation($relation);
    }
961594
public function assignRole(...$roles)
    {
        $roles = collect($roles)
            ->flatten()
            ->map(function ($role) {
                if (empty($role)) {
                    return false;
                }

                return $this->getStoredRole($role);
            })
            ->filter(function ($role) {
                return $role instanceof Role;
            })
            ->each(function ($role) {
                $this->ensureModelSharesGuard($role);
            })
            ->map->id
            ->all();

        $model = $this->getModel();

        if ($model->exists) {
            $this->roles()->sync($roles, false);
            $model->load('roles');
        } else {
            $class = \get_class($model);

            $class::saved(
                function ($object) use ($roles, $model) {
                    static $modelLastFiredOn;
                    if ($modelLastFiredOn !== null && $modelLastFiredOn === $model) {
                        return;
                    }
                    $object->roles()->sync($roles, false);
                    $object->load('roles');
                    $modelLastFiredOn = $object;
                });
        }

        $this->forgetCachedPermissions();

        return $this;
    }
804747
public function roleList()
    {
        $body = $this->request(self::URI_AUTH_ROLE_LIST);

        if ($this->pretty && isset($body['roles'])) {
            return $body['roles'];
        }

        return $body;
    }
259586
public function rolePermissions()
    {
        $permissionModel = app(config('roles.models.permission'));

        if (!$permissionModel instanceof Model) {
            throw new InvalidArgumentException('[roles.models.permission] must be an instance of \Illuminate\Database\Eloquent\Model');
        }

        return $permissionModel::select(['permissions.*', 'permission_role.created_at as pivot_created_at', 'permission_role.updated_at as pivot_updated_at'])
                ->join('permission_role', 'permission_role.permission_id', '=', 'permissions.id')->join('roles', 'roles.id', '=', 'permission_role.role_id')
                ->whereIn('roles.id', $this->getRoles()->lists('id')->toArray()) ->orWhere('roles.level', '<', $this->level())
                ->groupBy(['permissions.id', 'pivot_created_at', 'pivot_updated_at']);
    }