10

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.

Binit Ghetiya
  • 1,919
  • 2
  • 21
  • 31
aleXela
  • 1,270
  • 2
  • 21
  • 34

2 Answers2

4

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.

B Faley
  • 17,120
  • 43
  • 133
  • 223
Surahman
  • 1,040
  • 9
  • 15
2

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

Binit Ghetiya
  • 1,919
  • 2
  • 21
  • 31
  • I do know about the pivot table. But I didn't find function or property like $user-addUsergroup('groupname'); I know that I can make straight way - update(table .. bla bla ). I was sure that there is simple way. And most "October" way – aleXela Nov 23 '16 at 19:37