PHP code example of metrial / laravel-rbac

1. Go to this page and download the library: Download metrial/laravel-rbac library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

metrial / laravel-rbac example snippets




// app/Models/User.php — added by rbac:install
namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Metrial\RBAC\Traits\HasRoles;
use Metrial\RBAC\Traits\HasPermissions;

class User extends Authenticatable
{
    use HasRoles, HasPermissions;
}

// Create roles and permissions
use Metrial\RBAC\Facades\Rbac;

$admin = Rbac::role()->create(['name' => 'Admin', 'slug' => 'admin']);
$editPosts = Rbac::permission()->create(['name' => 'edit-posts', 'group' => 'posts']);

// Assign permission to role
Rbac::role()->assignPermission($admin, $editPosts->id);

// Assign role to user
$user->assignRole('admin');

// Check authorization
$user->hasRole('admin');           // true
$user->hasPermissionTo('edit-posts'); // true
$user->can('edit-posts');          // true (Gate)

return [

    // The authenticatable model that receives the HasRoles trait.
    'user_model' => env('RBAC_USER_MODEL', App\Models\User::class),

    // Super-admin role name. Set to null to disable.
    // Every bypass is logged to the audit log with action `superadmin.bypass`.
    'super_admin_role' => env('RBAC_SUPER_ADMIN_ROLE', null),

    // Cache settings (reads are always cached)
    'cache' => [
        'enabled'    => env('RBAC_CACHE_ENABLED', true),
        'store'      => env('RBAC_CACHE_STORE', config('cache.default')),
        'ttl'        => env('RBAC_CACHE_TTL', 300), // 5 minutes default
        'version_key'=> 'rbac:schema_version',      // bump to nuke all
    ],

    // Database table names
    'tables' => [
        'teams'             => 'teams',
        'roles'             => 'roles',
        'permissions'       => 'permissions',
        'role_permission'   => 'role_permission',
        'role_hierarchy'    => 'role_hierarchy',
        'model_roles'       => 'model_roles',
        'model_permissions' => 'model_permissions',
        'model_teams'       => 'model_teams',
        'audit_log'         => 'rbac_audit_log',
    ],

    // Auto-register every permission as a Gate ability at boot.
    'gate_mode' => 'auto', // "auto" or "explicit"

    // Teams
    'teams' => [
        'enabled'           => true,
        'strict'            => false, // reject permissions without team_id
        'user_primary_team' => true,  // auto-set first team as primary
    ],

    // Audit logging
    'audit' => [
        'enabled'    => true,
        'queue'      => false, // dispatch audit writes to queue?
        'prune_after' => 90,   // days; 0 = never
    ],
];

use Metrial\RBAC\Facades\Rbac;
use Metrial\RBAC\Models\Role;

// Create a role
$role = Rbac::role()->create([
    'name'       => 'Editor',
    'slug'       => 'editor',
    'guard_name' => 'web',
    'level'      => 20,
]);

// Find a role
$role = Rbac::role()->findBySlug('editor');
$role = Rbac::role()->findById('uuid-here');

// Get all roles (optionally filtered by guard)
$roles = Rbac::role()->getAllRoles('web');

use Metrial\RBAC\Facades\Rbac;
use Metrial\RBAC\Models\Permission;

// Create a permission
$perm = Rbac::permission()->create([
    'name'       => 'edit-posts',
    'guard_name' => 'web',
    'group'      => 'posts',
]);

// Find a permission
$perm = Rbac::permission()->findByName('edit-posts');
$perm = Rbac::permission()->findById('uuid-here');

// Get all permissions grouped by `group` column
$grouped = Rbac::permission()->allGrouped('web');
// ['posts' => Collection, 'users' => Collection, ...]

// Get flat collection of permission names
$names = Rbac::permission()->getAllPermissionNames('web');

// Assign a role to a user
$user->assignRole('editor');
$user->assignRole($roleInstance);
$user->assignRole('editor', team: $team);
$user->assignRole('editor', team: $team, startsAt: now(), expiresAt: now()->addDays(30));

// Remove a role (all assignments for this slug across all teams and time windows)
$user->removeRole('editor');
$user->removeRole('editor', team: $team); // only in this team

// Sync roles (replace all with new set)
$user->syncRoles(['editor', 'reviewer']);
$user->syncRoles($roleCollection, team: $team);

// Direct permissions
$user->givePermissionTo('edit-posts');
$user->givePermissionTo('edit-posts', team: $team, expiresAt: now()->addWeek());
$user->revokePermissionTo('edit-posts');
$user->syncPermissions(['edit-posts', 'publish-posts']);

// Role checks
$user->hasRole('editor');                        // bool
$user->hasRole('editor', team: $team);           // bool (team-scoped)
$user->hasAllRoles(['editor', 'admin']);         // bool (must have ALL)
$user->hasAnyRole(['editor', 'reviewer']);       // bool (must have ANY)

// Permission checks
$user->hasPermissionTo('edit-posts');            // bool (                  // bool

use Metrial\RBAC\Models\Team;

// Create a team
$team = Rbac::team()->create([
    'name' => 'Acme Corp',
    'slug' => 'acme-corp',
]);

// Add/remove members
$user->addToTeam($team, asOwner: true);
$user->removeFromTeam($team);

// Check membership
$user->isMemberOf($team);   // bool
$user->isOwnerOf($team);    // bool

// Switch team context (affects all downstream permission resolution)
$user->switchTeam($team);
$user->getActiveTeamId(); // returns the team's UUID

$editor = Rbac::role()->create(['name' => 'Editor', 'slug' => 'editor']);
$admin  = Rbac::role()->create(['name' => 'Admin',  'slug' => 'admin']);

// Make admin a parent of editor
Rbac::role()->setParent($editor, $admin);

// Now editor inherits all of admin's permissions automatically
// Cycle detection throws RoleCycleException if you try to create a loop
$descendants = Rbac::role()->getChildRoles($editor->id);
$ancestors  = Rbac::role()->getParentRoles($editor->id);

// Assign for 30 days only
$user->assignRole('editor', startsAt: now(), expiresAt: now()->addDays(30));

// Assign permission for 1 week
$user->givePermissionTo('temp-access', expiresAt: now()->addWeek());

// Future-dated (not active yet)
$user->assignRole('editor', startsAt: now()->addMonth());

use Illuminate\Support\Facades\Route;

// Role-based
Route::get('/admin', [AdminController::class, 'index'])
    ->middleware('rbac.role:admin');

// Any of the listed roles
Route::get('/moderation', [ModController::class, 'index'])
    ->middleware('rbac.role:admin,moderator');

// Permission-based
Route::resource('posts', PostController::class)
    ->middleware('rbac.permission:edit-posts');

// Team context (user must be a member; sets team context for downstream resolution)
Route::get('/teams/{team}/analytics', [AnalyticsController::class, 'index'])
    ->middleware('rbac.team');

// Combined
Route::get('/reports', [ReportController::class, 'index'])
    ->middleware(['auth', 'rbac.role:admin', 'rbac.permission:view-reports']);

// In controllers
$this->authorize('edit-posts');

// In policies
public function update(User $user, Post $post): bool
{
    return $user->can('edit-posts');
}

// In Blade
@can('edit-posts')
    <a>Edit</a>
@endcan

// Direct check
if ($user->can('edit-posts')) { ... }
if ($user->cant('delete-posts')) { ... }

use Metrial\RBAC\Facades\Rbac;

// Service access
Rbac::role()->create([...]);
Rbac::permission()->findBySlug('edit-posts');
Rbac::team()->addMember($team, $user);
Rbac::audit()->forUser($user);

// Query audit logs for a user
$logs = Rbac::audit()->forUser($user, limit: 50);

// Prune logs older than 90 days
php artisan rbac:audit:prune --days=90
bash
php artisan rbac:install
bash
php artisan migrate
bash
php artisan db:seed --class=Metrial\\RBAC\\Seeders\\RbacDefaultSeeder
bash
php artisan vendor:publish --tag=rbac-config
bash
# Run manually
php artisan rbac:prune-expired

# Or schedule it in app/Console/Kernel.php
$schedule->command('rbac:prune-expired')->everyMinute();
bash
php vendor/bin/phpunit packages/metrial/rbac/tests/