spicykimchi
spicykimchi

Reputation: 1151

Update user group on Laravel Sentry

I have a dynamic checkboxes and wanted to update the User Group on Laravel Sentry using PUT method. Somehow the same as this no working code.

$array_of_group_id = [1,2,3];

$user = Sentry::findUserById(1);

// Find the group using the group id
$updateGroup = Sentry::findGroupById($array_of_group_id);

// Assign the group to the user
if ($user->updateGroup($updateGroup ))
{
    // Group assigned successfully
}
else
{
    // Group was not assigned
}

Upvotes: 0

Views: 599

Answers (1)

spicykimchi
spicykimchi

Reputation: 1151

This answer my question. https://github.com/cartalyst/sentry/issues/219

// Get the current user groups
$userGroups = $user->groups()->lists('group_id');

// Get the selected groups
$selectedGroups = Input::get('groups', array());

$groupsToAdd    = array_diff($selectedGroups, $userGroups);
$groupsToRemove = array_diff($userGroups, $selectedGroups);

// Assign the user to groups
foreach ($groupsToAdd as $groupId)
{
    $group = Sentry::getGroupProvider()->findById($groupId);

    $user->addGroup($group);
}

// Remove the user from groups
foreach ($groupsToRemove as $groupId)
{
    $group = Sentry::getGroupProvider()->findById($groupId);

    $user->removeGroup($group);
}

Upvotes: 2

Related Questions