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

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?