Module: EVENT_AFTER_SAVE_ELEMENT won't detect changed user group Event::on(\craft\services\Elements::class, \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) {
    if ($event-&gt;element instanceof \craft\elements\User) {
        $user = Craft::$app-&gt;getUsers()-&gt;getUserById($event-&gt;element-&gt;id);
        if ($user-&gt;isInGroup('abc')) {
            // Do something
        } else {
            // Do something different
        }
    }
});


I created a C3 module on pluginfactory.io. The code above works just fine in detecting when a user is saved/updated.

For sake of simplicity I have two user groups 1) abc 2) def.

When I uncheck the user from def and check him into abc (or the other way around), and save the user, my code won't register that the user group has changed, but thinks the user is still in the previously selected group. If I re-save the user (without changing groups), suddenly the code sees the correct group.

I assume that despite using EVENT_AFTER_SAVE_ELEMENT, the system still saves the user group change to the db after the Event triggers. Could that be it?

It's weird though, because any other field I pull from the user, e.g. if I change their email, my code is able to pick up the new email on the first save, so why not the change in user group?

Any assistance is greatly appreciated,
cheers!

Edit: Made problem clearer to understand.
That's because groups are not attached to the user directly. At the moment Craft stores the user it hasn't handled the permissions not the user groups.

The workflow is


Handling all kinds of variables and data
Fetch/Create a user
Populate the new field values for the user
Store the user
Handle verifications such as sending them an email
Assign the user to groups and grant them permissions


At the moment your event triggers the user wasn't assigned to the groups.

If you want to change users depending on their groups you should use the  Users::EVENT_AFTER_ASSIGN_USER_TO_GROUPS event