How can I update change user's group? simply cant find it. spent couple hours.
$user = new User;
$user->group = 'new';
$user->save();
User is in relation with belongsToMany with Group.
Not working. Thanks.
I think you can extend User model to add addUserGroup
method like this;
public function boot()
{
User::extend(function($model) {
$model->addDynamicMethod('addUserGroup', function($group) use ($model) {
if ($group instanceof Collection) {
return $model->groups()->saveMany($group);
}
if (is_string($group)) {
$group = UserGroup::whereCode($group)->first();
return $model->groups()->save($group);
}
if ($group instanceof UserGroup) {
return $model->groups()->save($group);
}
});
});
}
So you can add group to user with; group model instance, model collection and string of model code.
i have looked into october rainlab user class.
User Class is linked with Group class via belongstoMany relation.
public $belongsToMany = [
'groups' => ['RainLab\User\Models\UserGroup', 'table' => 'users_groups'],
'address' => [
'\codework\users\models\Address',
'table'=>'codework_users_user_address',
'order'=>'addr'
]
];
So when you are adding User to any group please make sure you have that group already created into your database.
Table name user_groups : this will contain all group in which user can be assigned.
Table name users_groups : this is a pivot table which contains relation between user and group table.
Hope this will help :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With