Adding members to a group dynamically in Drupal 8 I am trying add members to a group programmatically using Groups module in Drupal 8, and I am doing the following to achieve this:

use Drupal\Core\Entity\ContentEntityBase;
$roles = array('test_role');
$values = ['group_roles' =&gt; $roles, 'gid' =&gt; 1];
$account = $this-&gt;createUser();
$group = \Drupal\group\Entity\Group::load(1);
$group-&gt;addMember($account, $values);


So, users are already present in the site. I want to add only those users to a group who have successfully paid for it. Hence, I am trying to write a custom solution that I add a user to an already existing group on the site. I came across this addMember($account, $values) function in the group module, however am still not sure on what values its arguments ($account and $values) take. Above piece of code does not add users to my group. Can someone please suggest what wrong I am doing here?
So, modifying the code a little bit and saving the group after adding member to it worked for me. Pasting the updated code below:

use Drupal\Core\Entity\ContentEntityBase;
$account = \Drupal\user\Entity\User::load(\Drupal::currentUser()-&gt;id());
$group = \Drupal\group\Entity\Group::load($group_id);
$group-&gt;addMember($account);
$group-&gt;save();