Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update user group OctoberCMS rainlab user plugin

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.

like image 319
aleXela Avatar asked Nov 21 '16 22:11

aleXela


2 Answers

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.

like image 168
Surahman Avatar answered Nov 01 '22 20:11

Surahman


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 :)

like image 2
Binit Ghetiya Avatar answered Nov 01 '22 21:11

Binit Ghetiya