DEV Community

Cover image for Login, roles and permissions in Laravel, the setup I reuse on every project
Mehedi Mansur Rafi
Mehedi Mansur Rafi

Posted on

Login, roles and permissions in Laravel, the setup I reuse on every project

Part 4 of Laravel in Production.

Every admin panel I build reaches the same week. The owner starts as the only user, then staff need accounts: a receptionist who books appointments, a manager who sees reports, and someone who must never open the settings page. I run the same small setup each time. It is the setup behind the admin screens in AdminForge, and a larger version of it runs the hospital system I sell, where seven roles share one database.

No package is required. Two tables, a pivot, one middleware, and one policy cover most small panels. If your app grows past this, the shape still holds and a package can take over later.

Plan the roles on paper first

Write the roles as a table before any code. One row per screen or action, one column per role, and a plain yes or no in each cell. For a clinic panel mine looks like this:

Action Admin Manager Staff
View patients yes yes yes
Book appointments yes yes yes
Edit billing yes yes no
View reports yes yes no
Manage users yes no no
Change settings yes no no

This table does two jobs. The client agrees to it before I build, so access arguments end early. Later it becomes the test sheet: every cell is one login and one check.

Name permissions after the action

Permissions get names in one fixed pattern: the resource, a dot, the action. patients.view, patients.create, billing.edit, settings.update, users.manage. The pattern matters more than the list. A new screen gets a predictable name, and a search for billing. in the code finds every billing check in seconds.

Avoid role names inside permission checks. The day a manager also needs billing access, if role is manager edits spread across the app. A permission moves by changing one row in a table.

The tables

One role per user is enough for the panels I build, so users carry a role_id. Permissions attach to roles through a pivot.

Schema::create('roles', function (Blueprint $table) {
    $table->id();
    $table->string('name');        // Admin
    $table->string('slug')->unique(); // admin
    $table->timestamps();
});

Schema::create('permissions', function (Blueprint $table) {
    $table->id();
    $table->string('name')->unique(); // patients.view
    $table->timestamps();
});

Schema::create('permission_role', function (Blueprint $table) {
    $table->foreignId('permission_id')->constrained()->cascadeOnDelete();
    $table->foreignId('role_id')->constrained()->cascadeOnDelete();
    $table->primary(['permission_id', 'role_id']);
});
Enter fullscreen mode Exit fullscreen mode

The Role model holds a permissions() belongsToMany relation, and the User model gets one method that every check in the app goes through:

public function hasPermission(string $name): bool
{
    return $this->role
        ->permissions
        ->contains('name', $name);
}
Enter fullscreen mode Exit fullscreen mode

Keep this method boring. Caching can come later; a clear check you can read at 2 am is worth more.

Block routes with middleware

Register a middleware alias in bootstrap/app.php (Laravel 11 and 12 style):

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'permission' => \App\Http\Middleware\CheckPermission::class,
    ]);
})
Enter fullscreen mode Exit fullscreen mode

The middleware itself is short:

public function handle(Request $request, Closure $next, string $permission): mixed
{
    if (! $request->user()?->hasPermission($permission)) {
        abort(403);
    }

    return $next($request);
}
Enter fullscreen mode Exit fullscreen mode

Routes then state their rule where a reader can see it:

Route::middleware(['auth', 'permission:settings.update'])
    ->get('/settings', [SettingController::class, 'index']);
Enter fullscreen mode Exit fullscreen mode

First test: sign in as staff and type the settings address by hand. A 403 from the server is the pass mark. A hidden menu link is not. Menu hiding is display work, and it still matters for a clean screen, but the server check is the security.

AdminForge roles matrix screen, the grid of roles against permissions

Check again inside a policy

Middleware guards the door. A policy guards the record, for the cases where a role can open a list but only some rows are theirs. A doctor sees patients assigned to them, as an example:

class PatientPolicy
{
    public function view(User $user, Patient $patient): bool
    {
        if (! $user->hasPermission('patients.view')) {
            return false;
        }

        return $user->is_super_admin
            || $patient->doctor_id === $user->doctor?->id
            || $user->role->slug !== 'doctor';
    }
}
Enter fullscreen mode Exit fullscreen mode

Call it in the controller with $this->authorize('view', $patient); and Laravel returns the same 403. Two layers look like extra work until the first time a route gets reused by a new screen and the policy still holds.

One super admin, protected by rules

Every panel needs one account that can fix access itself. I keep exactly one super admin, marked by an is_super_admin flag on the user, and a Gate rule that lets that account pass every check:

Gate::before(function (User $user, string $ability) {
    return $user->is_super_admin ? true : null;
});
Enter fullscreen mode Exit fullscreen mode

Returning null matters: the normal checks still run for everyone else. Around this account sit three hard rules. The flag is never set from a form in the panel. The super admin account cannot be deactivated or deleted while signed in as itself. And its email is the owner's real inbox, so the password reset path always works. The setup stays honest: one known door back in, guarded well, instead of back doors in the code.

Seed the first admin, then lock the seeder down

The first admin comes from a seeder that reads its values from the environment file, never from values typed into the code:

User::updateOrCreate(
    ['email' => env('ADMIN_EMAIL')],
    [
        'name' => env('ADMIN_NAME', 'Admin'),
        'password' => Hash::make(env('ADMIN_PASSWORD')),
        'role_id' => Role::where('slug', 'admin')->value('id'),
        'is_super_admin' => true,
    ]
);
Enter fullscreen mode Exit fullscreen mode

Run it once on the server, then remove the password from the environment file and change it after the first login. A roles seeder runs alongside it, creating the roles and permissions from the paper table and attaching them, so a fresh install rebuilds the whole matrix with php artisan migrate --seed.

AdminForge user list showing the role badges for admin, manager, and staff accounts

Test every role with its own account

Create one real account per role and walk the paper table cell by cell. Sign in as staff, open the settings address by typing it, and write down the result. Sign in as manager and open the user list. Each row of the table gets one pass or fail mark, on the day the feature ships, not from memory later.

Two cells catch most faults. A staff account that can open a page by address means a route missed its middleware. A manager who gets a 403 on a page the table allows means a permission name drifted, usually a spelling difference between the seeder and the route. Both are five minute fixes on test day and half day hunts after launch.

AdminForge edit user screen with the role dropdown open

The mistakes that lock owners out of their own panels

Three faults come back again and again in panels I get asked to repair.

The first is gating the role pages themselves behind a permission, then editing that permission away. The admin removes users.manage from the admin role by accident, and the screen that would fix it now returns 403 for everyone. This is the job the protected super admin above exists for.

The second is deleting or deactivating the last admin account during a staff cleanup. Guard it in code: the app refuses to deactivate the only remaining admin, the same way it refuses to delete the super admin.

The third is quieter. The owner changes email, the old inbox dies, and the password reset link goes nowhere. A panel with no working reset path is one forgotten password away from a database edit. Keep the owner account on an inbox the owner controls, and test the reset mail once before handover. Panels break at the login screen more often than anywhere else; the deploy faults in my earlier post on Laravel routes returning 404 after a move (https://dev.to/mehedirafi/laravel-returns-404-on-every-route-after-deployment-here-is-the-fix-34p3) cost owners the same locked-out afternoon.

The short version

Plan the matrix on paper. Name permissions resource dot action. Check in middleware for the route and in a policy for the record. Keep one super admin behind hard rules, seed it once, and test every role with its own account before handover.

AdminForge already has the roles matrix and user pages built as Blade views. If you want the screens done and only the wiring left, it is $29 on Gumroad: https://mehedirafi.gumroad.com/l/adminforge


I am Mehedi Mansur Rafi, a freelance Laravel developer (B.Sc. in Computer Science & Engineering). I build hospital, clinic, and small business websites, and I fix Laravel sites through Upwork: https://www.upwork.com/freelancers/~0118ab607e0b4c599b. My store is at https://mehedirafi.gumroad.com/ and my site is https://mehedimansurrafi.online

Top comments (0)