PHP code example of saeedvir / laravel-permissions

1. Go to this page and download the library: Download saeedvir/laravel-permissions 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/ */

    

saeedvir / laravel-permissions example snippets




namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Saeedvir\LaravelPermissions\Traits\HasRolesAndPermissions;

class User extends Authenticatable
{
    use HasRolesAndPermissions;

    // ... rest of your User model
}

use Saeedvir\LaravelPermissions\Models\Role;
use Saeedvir\LaravelPermissions\Models\Permission;

// Create roles
$admin = Role::create([
    'name' => 'Administrator',
    'slug' => 'admin',
    'description' => 'Administrator role with full access'
]);

$editor = Role::create([
    'name' => 'Editor',
    'slug' => 'editor',
    'description' => 'Editor role'
]);

// Create permissions
$createPost = Permission::create([
    'name' => 'Create Post',
    'slug' => 'create-post',
    'description' => 'Can create posts'
]);

$editPost = Permission::create([
    'name' => 'Edit Post',
    'slug' => 'edit-post',
    'description' => 'Can edit posts'
]);

$deletePost = Permission::create([
    'name' => 'Delete Post',
    'slug' => 'delete-post',
    'description' => 'Can delete posts'
]);

// Give permissions to role
$admin->givePermissionTo('create-post', 'edit-post', 'delete-post');
$editor->givePermissionTo('create-post', 'edit-post');

// Or using Permission models
$admin->givePermissionTo($createPost, $editPost, $deletePost);

// Revoke permission
$editor->revokePermissionTo('edit-post');

// Sync permissions (removes old, adds new)
$editor->syncPermissions(['create-post']);

$user = User::find(1);

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

// Assign multiple roles
$user->assignRole('admin', 'editor');

// Or using Role models
$user->assignRole($admin, $editor);

// Assign role with expiration (NEW in v2.1.0)
$user->assignRoleUntil('premium', now()->addMonth());
$user->assignRoleUntil('trial-user', now()->addDays(7));

// Remove role
$user->removeRole('editor');

// Sync roles (removes old, adds new)
$user->syncRoles(['admin']);

$user = User::find(1);

// Give direct permission to user
$user->givePermissionTo('create-post');

// Give multiple permissions
$user->givePermissionTo('create-post', 'edit-post');

// Give permission with expiration
$user->givePermissionToUntil('create-post', now()->addWeek());

// Revoke permission
$user->revokePermissionTo('edit-post');

// Sync permissions
$user->syncPermissions(['create-post']);

$user = User::find(1);

// Check if user has role (automatically filters expired roles)
if ($user->hasRole('admin')) {
    // User is admin
}

// Check multiple roles (any)
if ($user->hasAnyRole(['admin', 'editor'])) {
    // User has at least one of these roles
}

// Check multiple roles (all)
if ($user->hasAllRoles(['admin', 'editor'])) {
    // User has all these roles
}

// Check permission (t + from active roles)
$permissions = $user->getAllPermissions();

'expirable_roles' => [
    'enabled' => env('PERMISSION_EXPIRABLE_ROLES_ENABLED', false),
],

use Carbon\Carbon;

// Assign temporary role
$user->assignRoleUntil('premium', now()->addMonth());
$user->assignRoleUntil('trial-user', now()->addDays(7));
$user->assignRoleUntil('seasonal-mod', Carbon::parse('2025-12-31'));

// Using role ID or model
$user->assignRoleUntil(1, now()->addWeeks(2));
$role = Role::where('slug', 'editor')->first();
$user->assignRoleUntil($role, now()->addMonths(6));

// All role checks automatically filter expired roles
$user->hasRole('premium'); // Returns false after expiration
$user->hasPermission('premium-feature'); // Also checks role expiration

// Query scopes also respect expiration
User::role('premium')->get(); // Only users with active premium role

'expirable_permissions' => [
    'enabled' => env('PERMISSION_EXPIRABLE_ENABLED', false),
],

// Give temporary permission
$user->givePermissionToUntil('create-post', now()->addWeek());
$user->givePermissionToUntil('beta-feature', now()->addDays(30));

// Permission automatically expires
$user->hasPermission('create-post'); // Returns false after expiration

'wildcard_permissions' => [
    'enabled' => env('PERMISSION_WILDCARD_ENABLED', false),
],

// Grant wildcard permission
$role->givePermissionTo('posts.*');

// Matches all post permissions
$user->hasPermission('posts.create'); // true
$user->hasPermission('posts.edit');   // true
$user->hasPermission('posts.delete'); // true

'super_admin' => [
    'enabled' => env('PERMISSION_SUPER_ADMIN_ENABLED', false),
    'role_slug' => env('PERMISSION_SUPER_ADMIN_SLUG', 'super-admin'),
],

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

// User now has ALL permissions
$user->hasPermission('any-permission'); // Always true

// Check if user is super admin
if ($user->isSuperAdmin()) {
    // User has unlimited access
}

// Get users with specific role
User::role('admin')->get();
User::role(['admin', 'editor'])->get();

// Get users with specific permission
User::permission('create-post')->get();
User::permission(['create-post', 'edit-post'])->get();

// Get users without role
User::withoutRole('banned')->get();

// Get users without permission
User::withoutPermission('delete-post')->get();

// Combine scopes
User::role('editor')
    ->permission('create-post')
    ->where('status', 'active')
    ->get();

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('check.auth');

//redirect to ./admin-login if Auth::check() === false
Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('check.auth:./admin-login');

// Single role
Route::get('/admin', function () {
    return view('admin.dashboard');
})->middleware('role:admin');

// Multiple roles (user needs at least one)
Route::get('/admin', function () {
    return view('admin.dashboard');
})->middleware('role:admin|super-admin');

// In route groups
Route::middleware(['role:admin'])->group(function () {
    Route::get('/users', [UserController::class, 'index']);
    Route::get('/settings', [SettingController::class, 'index']);
});

// Single permission
Route::post('/posts', [PostController::class, 'store'])
    ->middleware('permission:create-post');

// Multiple permissions (user needs at least one)
Route::put('/posts/{post}', [PostController::class, 'update'])
    ->middleware('permission:edit-post|edit-own-post');

// In route groups
Route::middleware(['permission:manage-posts'])->group(function () {
    Route::get('/posts', [PostController::class, 'index']);
    Route::post('/posts', [PostController::class, 'store']);
});

Route::middleware(['check.auth', 'role:admin', 'permission:delete-post'])
    ->delete('/posts/{post}', [PostController::class, 'destroy']);

'cache' => [
    'enabled' => env('PERMISSION_CACHE_ENABLED', true),
    'expiration_time' => env('PERMISSION_CACHE_EXPIRATION', 3600), // in seconds
    'key_prefix' => 'saeedvir_permissions',
    'store' => env('PERMISSION_CACHE_STORE', 'default'),
],

'middleware' => [
    'unauthorized_response' => [
        'type' => 'json', // 'json', 'redirect', 'abort'
        'redirect_to' => '/unauthorized',
        'abort_code' => 403,
        'json_message' => 'Unauthorized access.',
    ],
    'unauthenticated_response' => [
        'type' => 'redirect', // 'json', 'redirect', 'abort'
        'redirect_to' => '/login',
        'abort_code' => 401,
        'json_message' => 'Unauthenticated.',
    ],
],

'performance' => [
    'eager_loading' => true, // Enable eager loading for relationships
    'chunk_size' => 1000, // Chunk size for batch operations
],

use Saeedvir\LaravelPermissions\Services\PermissionCache;

$cache = app(PermissionCache::class);

// Clear specific user cache
$cache->clearUserCache($userId);

// Clear specific role cache
$cache->clearRoleCache($roleId);

// Flush all permission caches
$cache->flush();
bash
php artisan vendor:publish --tag=permissions-config
bash
php artisan migrate
bash
php artisan vendor:publish --tag=permissions-migrations
php artisan migrate