更新Laravel Sentry上的用户组

时间:2014-11-03 21:45:40

标签: laravel cartalyst-sentry

我有一个动态复选框,想要使用PUT方法更新Laravel Sentry上的用户组。 不知怎的,这个没有工作代码。

$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
}

1 个答案:

答案 0 :(得分:2)

这回答了我的问题。 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);
}