Core Concepts

Assigning Roles to Users

On this page

Each user has one role, stored in user_roles. Assign it from Admin → Users (/systemroles/admin/roles/users) or from code.

The Users screen#

A searchable, paginated table (DataTables, loaded by AJAX from POST /systemroles/admin/roles/userdata) with:

Column Source
ID users.id
Name users.name
E-mail users.email
Role The user's role, or "No Role"
Register Date users.created_at
Manage Assign Permission button, plus a "Manage" link if user_manage_url is set

Search matches name and email. Up to 1,000 rows load per page.

Assigning a role#

  1. Click Assign Permission on the user's row.
  2. Pick the role.
  3. Click Save Role.

What happens, in one database transaction:

  1. The user's user_roles row is updated, or created if they had none. role_admin is set to the id of the admin who made the change, and role_type to system if empty.
  2. A row is added to user_roles_history.
  3. The user's rows in user_roles_in are rebuilt from the new role's permissions. Rows from the old role are removed.

Doing it in code#

The admin screen's logic lives in the controller. In your own code, do the same three steps. A small service keeps it in one place:

PHP
namespace App\Services;

use BabeRuka\SystemRoles\Models\SystemRolesIn;
use BabeRuka\SystemRoles\Models\UserRoleHistory;
use BabeRuka\SystemRoles\Models\UserRoles;
use BabeRuka\SystemRoles\Models\UserRolesIn;
use Illuminate\Support\Facades\DB;

class AssignRole
{
    public function handle(int $userId, int $roleId, ?int $adminId = null): UserRoles
    {
        return DB::transaction(function () use ($userId, $roleId, $adminId) {
            $row = UserRoles::where('user_id', $userId)->orderBy('role_id')->first() ?? new UserRoles();
            $row->user_id    = $userId;
            $row->user_role  = $roleId;
            $row->role_admin = $adminId ?? auth()->id();
            $row->role_type  = $row->role_type ?: 'system';
            $row->save();

            // UserRoleHistory has no $fillable, so set the attributes one by one.
            $history = new UserRoleHistory();
            $history->role_id    = $row->role_id;
            $history->user_id    = $userId;
            $history->user_role  = $roleId;
            $history->role_admin = $row->role_admin;
            $history->role_type  = $row->role_type;
            $history->save();

            $permissions = SystemRolesIn::where('role_id', $roleId)->get();
            foreach ($permissions as $p) {
                UserRolesIn::updateOrCreate(
                    ['user_id' => $userId, 'in_id' => $p->in_id],
                    ['in_role' => (int) $p->in_role]
                );
            }
            UserRolesIn::where('user_id', $userId)
                ->whereNotIn('in_id', $permissions->pluck('in_id'))
                ->delete();

            return $row;
        });
    }
}

Giving new users a default role#

Assign a role when a user registers, for example in a listener for Laravel's Registered event:

PHP
use Illuminate\Auth\Events\Registered;

class AssignDefaultRole
{
    public function handle(Registered $event): void
    {
        app(\App\Services\AssignRole::class)->handle($event->user->id, 4, $event->user->id); // 4 = User
    }
}

Or from a model observer on created.

Reading a user's role#

PHP
use BabeRuka\SystemRoles\Services\SystemRolesService;
use BabeRuka\SystemRoles\Models\UserRoles;

$roleId = SystemRolesService::roleIdForUser($user->id);   // 0 if none

$role = UserRoles::where('user_id', $user->id)->first()?->role;  // SystemRoles model or null
$role?->role_name;

Adding a relationship to your User model makes this easier:

PHP
use BabeRuka\SystemRoles\Models\UserRoles;

public function systemRole()
{
    return $this->hasOne(UserRoles::class, 'user_id', 'id');
}

// $user->systemRole?->role?->role_guard_name

Role history#

user_roles_history keeps every assignment:

PHP
use BabeRuka\SystemRoles\Models\UserRoleHistory;

UserRoleHistory::where('user_id', $user->id)->latest()->get();
Column Meaning
role_id The user_roles row id
user_id The user
user_role The role given
role_admin Who gave it
role_type Copied from user_roles
created_at When

About user_roles_in#

user_roles_in is a snapshot of the user's permissions taken when their role is assigned. It is not updated when you later change the role's permissions in the matrix. For permission checks, use roleHas(), which reads the live matrix in system_roles_in. Treat user_roles_in as a record, not as the source of truth.

Deleting users#

user_roles and user_roles_in have foreign keys to users.id with ON DELETE RESTRICT. Delete a user's rows in those two tables before deleting the user, or switch to soft deletes.