Search by

buildwithsmk / laravel-tenant-permission

buildwithsmk

Roles and permissions for Laravel. Works as plain RBAC in a single app, or tenant-scoped RBAC in a multi-tenant app. Per-user grant/deny overrides, Super Admin and tenant-admin bypass, and an optional built-in management UI.

Package info

github.com/MSumon89/laravel-tenant-permission

pkg:composer/buildwithsmk/laravel-tenant-permission

Statistics

Installs: 9

Dependents: 1

Suggesters: 1

Stars: 0

Open Issues: 0

v1.1.1 2026-11-24 07:59 UTC

This package is auto-updated.

Last update: 2026-11-24 08:00:21 UTC


README

Roles and permissions for Laravel 11, 12 and 13 that work the same way in two kinds of app:

Single app (default) Multi-tenant (PERMISSION_TENANCY=true)
Roles One shared set A separate set per tenant (shop, clinic, hotel, account…) plus optional global roles
Users Any number of roles Any number of roles within their tenant
Super Admin Passes every check Passes every check, in every tenant
"Full access" role (is_admin) Holds every permission Holds every permission in its own tenant
Per-user overrides Grant / deny single permissions Same, per tenant

Effective permissions = role permissions + direct grants − direct denies. A deny always wins.

Also included:

  • Optional branches (PERMISSION_BRANCHES=true), in either mode: HQ users switch between branches or see all of them, branch users are automatically limited to their own, and roles can be given per branch. It uses your own branch table. See section 4.
  • @can, $user->can(), $this->authorize() work with permission names out of the box.
  • Route middleware: permission: and tenant_role:.
  • Per-user caching that invalidates itself. Your app cache is never flushed.
  • Optional management UI (roles, permission catalog, user access) with publishable views.

1. Install

composer require buildwithsmk/laravel-tenant-permission
php artisan permission:install          # publishes config/permission.php

composer require ends with a reminder to run permission:install. The reminder stops once config/permission.php exists.

Before migrating, open config/permission.php:

  • Multi-tenant app? Set PERMISSION_TENANCY=true in .env.
  • Change table_names now if you need to (e.g. spatie/laravel-permission is also installed, because both use roles, permissions, …).
php artisan migrate

The migrations load automatically from the package, so you don't need to publish them. They are safe to run on a database that already has the tables. To keep editable copies in your app, run php artisan permission:install --migrations.

Add the trait to your User model:

use BuildWithSmk\TenantPermission\Traits\HasRolesAndPermissions;

class User extends Authenticatable
{
    use HasRolesAndPermissions;
}

Seed the basics and make yourself Super Admin:

php artisan db:seed --class="BuildWithSmk\TenantPermission\Database\Seeders\PermissionSeeder"
php artisan permission:super-admin you@example.com

2. Single-app usage (no tenancy)

use BuildWithSmk\TenantPermission\Models\Permission;
use BuildWithSmk\TenantPermission\Models\Role;

// Seeder: your permission catalog ("<module>.<action>")
foreach (['posts', 'users'] as $module) {
    foreach (['view', 'create', 'edit', 'delete'] as $action) {
        Permission::findOrCreate("{$module}.{$action}");
    }
}

Role::findOrCreate('Editor')->givePermissionTo('posts.view', 'posts.edit');
Role::findOrCreate('Admin')->update(['is_admin' => true]); // every permission

$user->assignRole('Editor');
$user->hasPermissionTo('posts.edit');   // true
$user->can('posts.edit');               // true (Gate)

That's all. With tenancy off, any tenant_id column on your users is ignored and everything lives in the global scope.

3. Multi-tenant usage

Set PERMISSION_TENANCY=true. The package then needs to know which tenant a check runs in. It looks in this order:

  1. A tenant pinned for the request: PermissionManager::setCurrentTenantId($id)
  2. The user's own tenant, from the resolver (default: $user->getTenantId() or the tenant_id column)
  3. Otherwise the global scope (platform staff, Super Admin)

Pick the setup that matches your app:

A. Each user belongs to one tenant, stored as a column (most common). If the column is tenant_id, there's nothing to do. For another name, either set tenancy.tenant_column, or implement the contract:

use BuildWithSmk\TenantPermission\Contracts\BelongsToTenant;

class User extends Authenticatable implements BelongsToTenant
{
    use HasRolesAndPermissions;

    public function getTenantId(): ?int
    {
        return $this->shop_id;
    }
}

B. Users can work in several tenants (tenant comes from subdomain, URL or session). Pin the current tenant in your own middleware, after you identify it:

use BuildWithSmk\TenantPermission\Facades\PermissionManager;

public function handle(Request $request, Closure $next)
{
    $tenant = Tenant::whereDomain($request->getHost())->firstOrFail();
    PermissionManager::setCurrentTenantId($tenant->id);

    return $next($request);
}

Run this middleware before any permission: middleware or @can checks. The value resets automatically after each request and job, including under Octane.

C. You already use a tenancy package. Write a resolver and point tenancy.resolver at it:

use BuildWithSmk\TenantPermission\Contracts\TenantResolver;

class CurrentTenantResolver implements TenantResolver
{
    public function resolve(Model $model): ?int
    {
        return tenant()?->getKey();
    }
}

Creating tenant roles, e.g. when a new tenant signs up:

$owner = Role::findOrCreate('Owner', $tenant->id);
$owner->update(['is_admin' => true, 'is_system' => true]); // full access, can't be deleted

Role::findOrCreate('Staff', $tenant->id)->givePermissionTo('rooms.view', 'bookings.create');

$user->assignRole('Owner');                 // resolved in the user's tenant
$user->assignRole('Staff', $otherTenantId); // or an explicit tenant

Global roles (tenant_id = 0) apply in every tenant. The permission catalog is always global and shared by all tenants.

Never use 0 as a real tenant id. It is the global scope (global_tenant_id).

4. Branches (HQ and branch offices)

For data that belongs to branches, such as a clinic group with an HQ and several branch clinics:

  • Branch users only ever see their own branch. Filtering is automatic.
  • HQ users pick a branch from a dropdown, or choose All branches for combined data.
  • A person has one login. Their roles can apply in every branch, or in one branch only.

This works with or without tenancy, and it uses your own branch table (offices, branches, outlets, …). The package stores branch ids only. With tenancy on, a check uses both the tenant and the branch.

PERMISSION_BRANCHES=true
php artisan migrate   # adds branch_id to the role/override pivots

1. Tell the package about your branches. If every user has a branch_id column and can only access that branch, there's nothing to do. Otherwise write a resolver and set branches.resolver:

use BuildWithSmk\TenantPermission\Contracts\BranchResolver;

class OfficeBranchResolver implements BranchResolver
{
    public function defaultBranchId(Model $user): ?int
    {
        return $user->office_id;
    }

    public function accessibleBranchIds(Model $user): array
    {
        return $user->office?->is_hq
            ? Office::where('parent_id', $user->office_id)->pluck('id')->push($user->office_id)->all()
            : [$user->office_id];
    }
}

For something smaller, implement HasBranches (getBranchId(), getAccessibleBranchIds()) on the User model instead.

2. Pick the branch per request. Append the middleware to the web group, so it runs before any permission: check:

// bootstrap/app.php
->withMiddleware(fn (Middleware $middleware) => $middleware->web(append: \BuildWithSmk\TenantPermission\Middleware\ResolveBranch::class))

It reads the choice from the session and checks it against the resolver. If the choice is missing or not allowed, it falls back to the home branch. All branches (0) is only allowed for users with more than one branch. Set branches.default_all to start HQ users there.

3. Filter your data. Add the trait to branch-owned models:

use BuildWithSmk\TenantPermission\Traits\BelongsToBranch;

class Patient extends Model
{
    use BelongsToBranch;

    protected string $branchColumn = 'office_id'; // default: branches.column
}

Patient::all();                          // selected branch, or every accessible branch in "All branches"
Patient::forBranch($id)->get();          // narrow further (per-branch report columns)
Patient::withoutBranchScope()->get();    // no filter (platform reports, console)

The branch column is filled in on create when one branch is selected. In "All branches" mode your form must send it. Validate it with in_array($id, PermissionManager::getAccessibleBranchIds()).

Requests with no branch context return no rows (branches.strict), so a route that forgot the middleware fails safe. Console commands and queue jobs aren't filtered unless you call PermissionManager::setCurrentBranchId($id).

4. The switch dropdown. POST branch_id (0 = All branches) to route('permission.branch.switch'). Branches the user can't access get a 403. The current values are available through PermissionManager::getCurrentBranchId() and getAccessibleBranchIds(). You render the branch names from your own table.

Branch-wise roles. Assignments made without a branch apply in every branch, like before. Give a branch to make one branch-only:

$user->assignRole('Doctor');                                    // every branch
$user->assignRole('Manager', branchId: $gulshan->id);           // Gulshan only
$user->denyPermissionTo('invoices.refund', branchId: $banani->id);

$user->hasPermissionTo('patients.edit');                        // current branch
$user->hasPermissionTo('patients.edit', branchId: $patient->office_id); // a row's branch, e.g. in a policy
Check in Counts
Branch X every-branch roles/overrides + branch-X ones
All branches every-branch roles/overrides only, so a Gulshan-only Manager gets no Manager rights in the combined list

A deny in either scope wins. An is_admin role assigned to one branch gives every permission in that branch only. The built-in UI manages every-branch assignments and leaves branch-only ones alone.

Branch id 0 means "every branch". Never use 0 as a real branch id.

5. API reference

On the user (every $tenantId is optional and defaults to the resolved scope). With branches, write methods take branchId: (default 0 = every branch), and check methods take branchId: (default = current branch):

Method
assignRole($role, $tenantId) / removeRole(...) $role = name or Role
syncRoles([...], $tenantId) names, ids or models. Only that tenant's (and branch's) roles are replaced
hasRole('Manager'), hasRole(['A', 'B']), hasAnyRole([...]) global roles count everywhere
getRoleNames(), rolesForTenant()
givePermissionTo('x') / denyPermissionTo('x') / clearPermissionOverride('x') direct overrides
syncPermissionOverrides(['x' => 'grant', 'y' => 'deny']) replace all overrides in a tenant
hasPermissionTo('x'), hasAnyPermission([...]), hasAllPermissions([...])
getAllPermissions(), getPermissionsViaRoles(), getPermissionOverrides()
isSuperAdmin(), isTenantAdmin()
resolveTenantId(), resolveBranchId() the scope a check would use

On a role: givePermissionTo('a', 'b'), revokePermissionTo(...), syncPermissions([...]), hasPermissionTo('a'), Role::findByName($name, $tenantId), Role::findOrCreate($name, $tenantId).

Routes:

Route::put('/posts/{post}', ...)->middleware('permission:posts.edit');
Route::get('/reports', ...)->middleware('permission:reports.view|reports.export'); // any of
Route::get('/till', ...)->middleware('tenant_role:Manager|Cashier');

Guests get a 401 (redirect to login). Users without access get a 403 (BuildWithSmk\TenantPermission\Exceptions\UnauthorizedException).

Blade: @can('posts.edit') … @endcan. No custom directive is needed.

Cache: handled for you. To reset it by hand, run php artisan permission:cache-reset.

6. The built-in UI (optional)

PERMISSION_UI=true

Then open /access-control. You get three screens:

  • Roles: create, edit and delete roles, with a permission picker grouped by module.
  • Users: assign roles, and set Inherit / Grant / Deny per permission. Shows the effective result.
  • Permissions: the catalog.

Who can do what (enforced on the server, not just hidden in the page):

Actor Can
Super Admin Everything, including the permission catalog and the Super Admin role
Admin (is_admin role in the scope) Everything in their scope. Catalog edits only in single-app mode
User with access-control.manage Manage roles and users, but only hand out permissions they hold themselves
Anyone else 403

With tenancy on, each person only sees their own tenant's roles and users (other tenants' records return 404), and only a Super Admin can change the global catalog. Nobody can remove their own admin role, so you can't lock yourself out.

Customising the look. There are three levels:

  1. Use your own layout. Point the config at a layout that @yields a section:
    'ui' => ['layout' => 'layouts.admin', 'section' => 'content'],
    The pages bring their own scoped CSS (.pm-* classes, light and dark), so they look right in any layout. You don't need Tailwind or a build step.
  2. Redesign the pages. Publish the views and edit them freely:
    php artisan vendor:publish --tag=permission-views
    They land in resources/views/vendor/permission/ and override the package's copies. Routes, controllers, validation and the security rules above stay in the package, so your redesigned forms keep working. Keep the input names (permissions[], roles[], overrides[<name>]).
  3. Build your own screens. Leave the UI off and call the API in section 5 from your own controllers.

Other UI options: prefix, route_name_prefix, middleware, per_page, user_display_column, user_search_columns. To scope the user list yourself (multi-tenant), add scopeInPermissionTenant(Builder $query, int $tenantId) to your User model. Otherwise tenancy.tenant_column is used.

7. Upgrading

From 1.0 to 1.1: run php artisan migrate. It adds branch_id (default 0) to model_has_roles and model_has_permissions. Nothing else changes until you set PERMISSION_BRANCHES=true. A published config/permission.php keeps working without changes, because the package's branches defaults are merged in. Copy the branches block over only if you want to edit it.

From the old in-repo copy

If your app used the earlier copy at packages/smk/permission:

  1. Multi-tenant apps must set PERMISSION_TENANCY=true. Tenancy is now opt-in. Without it, every check runs in the global scope.
  2. Remove the old path repository and smk/permission from your composer.json, run composer require buildwithsmk/laravel-tenant-permission, then php artisan migrate. Missing columns (roles.description, roles.is_admin) are added, and existing tables are left alone.
  3. The namespace changed from Smk\Permission to BuildWithSmk\TenantPermission. Search and replace it across your app (app/, config/, database/, routes/, tests/), including any published config/permission.php.
  4. Behaviour changes to know about:
    • getAllPermissions() and hasPermissionTo() now return all permissions for tenant admins, matching what the Gate and middleware already did.
    • hasRole() now also counts global roles.
    • PermissionRegistrar::forgetAll() no longer flushes the whole app cache.
    • The facade alias is PermissionManager (was Permission).

Requirements

PHP 8.2+, Laravel 11, 12 or 13.

License

MIT