PHP code example of amdadulhaq / custodian-laravel
1. Go to this page and download the library: Download amdadulhaq/custodian-laravel 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/ */
amdadulhaq / custodian-laravel example snippets
namespace App\Models;
use AmdadulHaq\Custodian\Contracts\Roleable as RoleableContract;
use AmdadulHaq\Custodian\Concerns\Roleable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements RoleableContract
{
use Roleable;
}
namespace App\Models;
use AmdadulHaq\Custodian\Contracts\Roleable as RoleableContract;
use AmdadulHaq\Custodian\Concerns\Roleable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements RoleableContract
{
use Roleable;
}
use AmdadulHaq\Custodian\Contracts\Roleable as RoleableContract;
use AmdadulHaq\Custodian\Concerns\Roleable;
class User extends Authenticatable implements RoleableContract
{
use Roleable;
}
use AmdadulHaq\Custodian\Models\Role;
// Set fields on create (or later via update())
$role = Role::create([
'name' => 'administrator', // tect from deletion
]);
$role->update(['label' => 'Admin']);
// Get fields
$role->getName(); // 'administrator'
$role->getLabel(); // 'Administrator'
$role->getDescription(); // 'Full system access'
$role->isProtectedRole(); // true — deleting now throws ProtectedRoleException
// Other role methods
$role->getPermissionNames(); // All permission names assigned to the role
$role->users; // Users with this role
// Query scopes
Role::protected()->get(); // Only protected roles
Role::unprotected()->get(); // Only unprotected roles
use AmdadulHaq\Custodian\Models\Permission;
// Set fields on create — only 'name' is nique — used by all checks
'label' => 'Delete Users', // optional display name
'description' => 'Permanently remove user accounts',
'group' => 'users', // optional; when empty it is filled from the first segment of the name on save
]);
// Wildcard permission — is_wildcard is set automatically when name ends with '*'
Permission::create([
'name' => 'posts.*',
'label' => 'Manage All Posts',
'group' => 'posts',
]);
// Get fields
$permission->getName(); // 'users.delete'
$permission->getLabel(); // 'Delete Users'
$permission->getDescription(); // 'Permanently remove user accounts'
$permission->getGroup(); // 'users' (derived from the name prefix)
$permission->isWildcard(); // false
$permission->getType(); // PermissionType::DELETE (from the last name segment)
$permission->roles; // Roles with this permission
// Query scopes — group permissions for an admin UI
Permission::wildcard()->get(); // Only wildcard permissions
Permission::byGroup('users')->get(); // All users.* permissions
Permission::all()->groupBy->getGroup(); // ['users' => [...], 'posts' => [...]]
// Create wildcard permission
Permission::create(['name' => 'posts.*']);
// Assign to role
$role->givePermissionTo('posts.*');
// Now user can do all of these:
$user->hasPermission('posts.create'); // true
$user->hasPermission('posts.update'); // true
$user->hasPermission('posts.delete'); // true
$user->hasPermission('posts.publish'); // true
// Single role
$user->assignRole('administrator'); // by role name
$user->assignRole($roleModel); // by role model
// Multiple roles in one call
$user->assignRole('administrator', 'editor');
$user->assignRole([$roleModel, $roleId, 'moderator']);
// A digit-only string is tried as an ID first, then as a name, so a
// role named "2024" still resolves when no role has ID 2024.
// Sync (replaces all)
$user->syncRoles(['administrator', 'editor']);
$user->syncRoles([$role1->id, $role2->id]);
// Sync without detaching existing
$user->syncRolesWithoutDetaching(['moderator']);
// Revoke
$user->revokeRole('editor');
$user->revokeRole($roleModel);
$user->revokeRoles(); // Revoke all
// Single role
$user->hasRole('administrator'); // true/false
// Multiple roles
$user->hasAllRoles(['admin', 'editor']); // Must have ALL
$user->hasAnyRole(['admin', 'moderator']); // Must have ANY
// Get role names
$user->getRoleNames(); // ['administrator', 'editor']
// Get role labels keyed by name (falls back to name when no label)
$user->getRoleLabels(); // ['administrator' => 'Administrator', 'editor' => 'editor']
// Single permission
$role->givePermissionTo('users.create'); // by permission name
$role->givePermissionTo($permissionModel); // by permission model
// Multiple permissions in one call
$role->givePermissionTo('users.create', 'users.edit');
$role->givePermissionTo([$permissionModel, $permissionId, 'users.delete']);
// Sync (replaces all)
$role->syncPermissions(['users.create', 'users.edit']);
$role->syncPermissions([$perm1->id, $perm2->id]);
// Revoke
$role->revokePermissionTo('users.delete');
$role->revokePermissionTo($permissionModel);
$role->revokeAllPermissions();
$role->hasPermission('users.edit'); // Exact match only: a role holding 'users.*' returns false here.
// Wildcards are resolved on the user: $user->hasPermission('users.edit')
$role->getPermissionNames(); // Get all permission names
// Check by name
$user->hasPermission('users.create');
// Check by model
$user->hasPermission($permissionModel);
// Wildcard matching
$user->hasPermission('posts.*');
// Get all permissions inherited from roles
$user->getPermissions();
// Get permission names array
$user->getPermissionNames(); // ['users.create', 'users.edit']
if ($user->hasRole('administrator')) {
// User has administrator role
}
if ($user->hasAllRoles(['admin', 'editor'])) {
// User has both roles
}
if ($user->hasAnyRole(['admin', 'moderator'])) {
// User has at least one role
}
// Get all role names
$user->getRoleNames(); // ['administrator', 'editor']
if ($user->hasPermission('users.create')) {
// User can create users
}
if ($user->hasPermission('posts.*')) {
// User has wildcard permission for posts
}
// Role middleware
Route::middleware('role:administrator')->get('/admin', [AdminController::class, 'index']);
// Guests get 401. A logged-in user whose model doesn't use Roleable gets 403.
// Multiple roles (('/users', [UserController::class, 'store']);
// Multiple permissions (ssion
Route::middleware('role_or_permission:admin,editor,posts.manage')->group(function () {
Route::post('/manage', [Controller::class, 'handle']);
});
// In controllers
public function store(Request $request)
{
$this->authorize('users.create');
// User can create users
}
// Using Gate facade
use Illuminate\Support\Facades\Gate;
if (Gate::allows('users.create')) {
// Allowed
}
if (Gate::denies('users.delete')) {
abort(403, 'Permission denied');
}
// Check for specific user
if (Gate::forUser($otherUser)->allows('posts.edit')) {
// That user can edit posts
}
// Authorize roles
$this->authorize('administrator');
// Users with a specific role
User::query()->withRoles('administrator')->get();
// Users with a specific permission inherited through roles
User::query()->withPermissions('users.create')->get();
// Role scopes
Role::query()->protected()->get();
Role::query()->unprotected()->get();
// Permission scopes
Permission::query()->wildcard()->get();
Permission::query()->byGroup('users')->get();
use AmdadulHaq\Custodian\Facades\Custodian;
Custodian::getSingularName('roles'); // 'role'
Custodian::getTableName(Role::class); // 'roles' (resolves the model's table)
Custodian::getPivotTableName([Role::class, User::class]); // 'role_user' (alphabetical)
use AmdadulHaq\Custodian\Exceptions\PermissionDeniedException;
use AmdadulHaq\Custodian\Exceptions\ProtectedRoleException;
// Thrown by the middleware when a user lacks the ssigned('administrator');
throw PermissionDeniedException::roleOrPermissionNotAssigned('admin, users.delete');
// Thrown when deleting a role with is_protected = true
throw ProtectedRoleException::cannotDelete('super-admin');
use AmdadulHaq\Custodian\Events\RoleAssigned;
use AmdadulHaq\Custodian\Events\RoleRevoked;
use AmdadulHaq\Custodian\Events\PermissionGranted;
use AmdadulHaq\Custodian\Events\PermissionRevoked;
// Dispatched by $user->assignRole()/syncRoles() and $user->revokeRole()/revokeRoles()
class RoleAssigned { public Model $subject; public array $roleIds; }
class RoleRevoked { public Model $subject; public ?Model $role; public array $roleIds; } // $role is null when all roles were revoked
// Dispatched by $role->givePermissionTo()/syncPermissions() and $role->revokePermissionTo()/revokeAllPermissions()
class PermissionGranted { public Model $role; public array $permissionIds; }
class PermissionRevoked { public Model $role; public ?Model $permission; public array $permissionIds; } // null when all permissions were revoked
// app/Providers/EventServiceProvider.php (or a listener class)
Event::listen(function (RoleAssigned $event) {
Log::info("Role(s) assigned to {$event->subject->getKey()}", ['role_ids' => $event->roleIds]);
});
bash
php artisan custodian:create-role admin Administrator
# Optionally assign it to a user by ID, email, or name
php artisan custodian:create-role moderator "Moderator" 1
php artisan custodian:create-role moderator "Moderator" [email protected]
php artisan custodian:create-role moderator "Moderator" "Jane Doe"
bash
php artisan custodian:upgrade
bash
php artisan custodian:doctor
bash
composer dump-autoload
bash
php artisan config:clear
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.