October CMS resources and help articles

Simple and to the point. Optimized by the community.

Switching the registered user group in a User model based on boolean input

0
by mohsin, last modified on January 5th, 2021

Given a registered flag that may arrive from an API or any other source, this block can be used to switch the registered flag. Directly calling add or remove causes exceptions so it's essential to check like this:

$registered = Input::get('is_registered');
$registeredGroup = \RainLab\User\Models\UserGroup::whereName('registered')->first();
if ($registered) {
    if (!$user->groups()->whereName('registered')->exists()) {
        $user->groups()->add($registeredGroup);
        $user->save();
    }
} else {
    if ($user->groups()->whereName('registered')->exists()) {
        $user->groups()->remove($registeredGroup);
        $user->save();
    }
}

Discussion

1 comment

1
daniloc
Post on November 7th, 2021 7:24 AM

You can force it without checking:

if ($registered)
{
    $this->user->groups()->syncWithoutDetaching([$registeredGroup->id]);
}
else
{
    $this->user->groups()->detach([$registeredGroup->id]);
}
$this->user->save();
We use cookies to measure the performance of this website. Do you want to accept these cookies?