PHP code example of squareetlabs / laravel-simple-permissions

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

    

squareetlabs / laravel-simple-permissions example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Squareetlabs\LaravelSimplePermissions\Traits\HasPermissions;

class User extends Model
{
    use HasPermissions;
    
    // ... rest of your code
}

'features' => [
    'groups' => [
        'enabled' => env('SIMPLE_PERMISSIONS_GROUPS_ENABLED', true),
    ],
    'abilities' => [
        'enabled' => env('SIMPLE_PERMISSIONS_ABILITIES_ENABLED', true),
    ],
],

'models' => [
    'user' => App\Models\User::class,
    // ... other models
],

'cache' => [
    'enabled' => env('SIMPLE_PERMISSIONS_CACHE_ENABLED', true),
    'driver' => env('SIMPLE_PERMISSIONS_CACHE_DRIVER', 'redis'),
    'ttl' => env('SIMPLE_PERMISSIONS_CACHE_TTL', 3600),
    'prefix' => 'simple_permissions',
    'tags' => true,
],

use Squareetlabs\LaravelSimplePermissions\Support\Facades\SimplePermissions;

// Create permissions
$viewPost = SimplePermissions::model('permission')::create(['code' => 'posts.view', 'name' => 'View Posts']);
$createPost = SimplePermissions::model('permission')::create(['code' => 'posts.create', 'name' => 'Create Posts']);

// Create role
$adminRole = SimplePermissions::model('role')::create(['code' => 'admin', 'name' => 'Administrator']);

// Assign permissions to role
$adminRole->permissions()->attach([$viewPost->id, $createPost->id]);

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

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

// Sync roles (replaces all existing roles)
$user->syncRoles(['admin', 'editor']);

// Give a permission directly to a user (even if their role doesn't have it)
$user->givePermission('posts.create');

// Revoke a permission directly from a user (even if their role has it)
$user->revokePermission('posts.edit');

// Remove a direct permission assignment (returns to role-based permissions)
$user->removePermission('posts.delete');

// Sync direct permissions (replaces all existing direct permissions)
$user->syncPermissions(['posts.create', 'posts.view']);

$user->assignRole('admin'); // Admin role has 10 permissions

// Option 1: Revoke (forbid) a permission - RECOMMENDED when user has roles
$user->revokePermission('posts.delete');
// Result: User has 9 permissions (posts.delete is forbidden)
// In DB: permission_user entry with forbidden=true

// Option 2: Remove permission assignment
$user->removePermission('posts.delete');
// Result: User still has 10 permissions (from admin role)
// In DB: No entry in permission_user for this permission

// Option 3: Give permission (override role)
$user->givePermission('posts.publish');
// Result: User has admin permissions + posts.publish
// In DB: permission_user entry with forbidden=false

// Check if user has a permission (direct or via role/group)
if ($user->hasPermission('posts.create')) {
    // User can create posts
}

// Check if user has a role
if ($user->hasRole('admin')) {
    // User is admin
}

// Check specific ability on an entity
if ($user->hasAbility('edit', $post)) {
    // User can edit this specific post
}

// Check if user has a role (or roles)
// $oles
$user->hasRole('admin', $has a permission (or permissions)
// $ser->hasPermission(['posts.create', 'posts.edit'], $st)

// Forbid ability for user on an entity
$user->forbidAbility('posts.edit', $post)

// Remove ability from user
$user->removeAbility('posts.edit', $post)

// Direct permissions (override role permissions)
$user->givePermission('posts.create')        // Grant permission directly
$user->revokePermission('posts.edit')         // Revoke permission directly (even if role has it)
$user->removePermission('posts.delete')       // Remove direct assignment (return to role-based)
$user->syncPermissions(['perm1', 'perm2'])   // Sync direct permissions

// Check multiple permissions (OR)
if ($user->hasPermission(['posts.create', 'posts.edit'], false)) {
    // User can create OR edit posts
}

// Check multiple permissions (AND)
if ($user->hasPermission(['posts.create', 'posts.edit'], true)) {
    // User can create AND edit posts
}

// Allow user to edit a specific post
$user->allowAbility('posts.edit', $post);

// Forbid user to edit a specific post
$user->forbidAbility('posts.edit', $post);

// Remove ability from user
$user->removeAbility('posts.edit', $post);

use Squareetlabs\LaravelSimplePermissions\Support\Facades\SimplePermissions;

// Create a permission first
$permission = SimplePermissions::model('permission')::create(['code' => 'posts.edit']);

// Create an ability for a specific entity
$ability = SimplePermissions::model('ability')::create([
    'permission_id' => $permission->id,
    'title' => 'Edit Post #1',
    'entity_id' => $post->id,
    'entity_type' => get_class($post),
]);

// Allow user to edit a specific post
$ability->users()->attach($user, ['forbidden' => false]);

// Forbid user to edit a specific post
$ability->users()->attach($user, ['forbidden' => true]);

// Remove ability from user
$ability->users()->detach($user);

if ($user->hasAbility('posts.edit', $post)) {
    // User can edit this specific post
}

use Squareetlabs\LaravelSimplePermissions\Support\Facades\SimplePermissions;

// Create group
$group = SimplePermissions::model('group')::create(['code' => 'moderators', 'name' => 'Moderators']);

// Assign permissions to group
$permission = SimplePermissions::model('permission')::where('code', 'posts.moderate')->first();
$group->permissions()->attach($permission);

// Add users to group
$group->users()->attach($user);

// Remove users from group
$group->users()->detach($user);

// Check role
Route::middleware(['role:admin'])->group(function () {
    Route::get('/admin', [AdminController::class, 'index']);
});

// Check permission
Route::middleware(['permission:posts.create'])->group(function () {
    Route::post('/posts', [PostController::class, 'store']);
});

// Check ability
// Format: ability:action,entity_class,route_parameter_name
Route::middleware(['ability:edit,App\Models\Post,post_id'])->group(function () {
    Route::put('/posts/{post_id}', [PostController::class, 'update']);
});

// User must have admin OR root
Route::middleware(['role:admin|root'])->group(function () {
    // ...
});

// In a controller
if ($user->can('view', $post)) {
    // User can view the post
}

// In a view
@can('update', $post)
    <button>Edit</button>
@endcan

use Squareetlabs\LaravelSimplePermissions\Events\RoleAssigned;
use Squareetlabs\LaravelSimplePermissions\Events\PermissionGranted;
use Squareetlabs\LaravelSimplePermissions\Events\AbilityGranted;

// In your EventServiceProvider
protected $listen = [
    RoleAssigned::class => [
        // Your listeners here
    ],
    PermissionGranted::class => [
        // Your listeners here
    ],
    AbilityGranted::class => [
        // Your listeners here
    ],
];

use Squareetlabs\LaravelSimplePermissions\Events\RoleAssigned;

class LogRoleAssignment
{
    public function handle(RoleAssigned $event)
    {
        // Log the role assignment
        Log::info("User {$event->user->id} was assigned role {$event->role->code}");
    }
}
bash
php artisan vendor:publish --provider="Squareetlabs\LaravelSimplePermissions\SimplePermissionsServiceProvider"
bash
php artisan migrate
bash
php artisan permissions:policy PostPolicy --model=Post