Problem with \craft\elements\User::EVENT_AFTER_SAVE Having an issue with using the event \craft\elements\User::EVENT_AFTER_SAVE in a plug in. I am adding a new user to a group. My goal is to have the newly added user automatically added to the same user group as the logged in user. This is my code:

Event::on(
    \craft\elements\User::class,
    \craft\elements\User::EVENT_AFTER_SAVE,
    function(ModelEvent  $event) {
        if (Craft::$app-&gt;getUser()-&gt;getIsAdmin() == false){
            $loggedInUser = Craft::$app-&gt;getUser();
            $userGroupUser = new UserGroup_User();
            $userGroupUser-&gt;groupId = $loggedInUser-&gt;getIdentity()-&gt;getGroups()[0]['id'];
            $userGroupUser-&gt;userId = $event-&gt;sender-&gt;id;
            $result = $userGroupUser-&gt;insert();
         }
    }
);


I have put a breakpoint on the code after the if statement and then checked the users table - the new user is not in the users table yet.

I would expect that the new user would be in the table at this point. Is this transaction being saved and executed later? If so is there something I can do to force the transaction to save the new user?

Is this possible a bug?

I do not get any error messages. Why?

EDIT: I should also mention that the usergroup has permission to add users in their own usergroup.
I don't know what your specific error is, but whenever I use

Event::on(
\craft\elements\User::class,
\craft\elements\User::EVENT_AFTER_SAVE,


I need to provide the next parameter with a \yii\base\Event callback, not a \craft\events\ModelEvent one.

Maybe that's your case as well ?
 You can also use \yii\base\ModelEvent, but not the craft one, as the craft ModelEvent does not extend \yii\base\Event