2014-11-03 78 views
0

我有一個動態複選框,並希望使用PUT方法更新Laravel Sentry上的用戶組。 不知何故,這與沒有工作代碼相同。更新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 
} 

回答

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); 
} 
+0

太棒了!儘管'removeAllGroups'函數很好,這是一個不錯的選擇 – developerbmw 2015-08-12 23:57:40