Download the PHP package amdadulhaq/custodian-laravel without Composer
On this page you can find all versions of the php package amdadulhaq/custodian-laravel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download amdadulhaq/custodian-laravel
More information about amdadulhaq/custodian-laravel
Files in amdadulhaq/custodian-laravel
Package custodian-laravel
Short Description Custodian is a role and permission management system for Laravel
License MIT
Homepage https://github.com/amdad121/custodian-laravel
Informations about the package custodian-laravel
Custodian - Modern Role & Permission Management for Laravel
A powerful, flexible, and developer-friendly role and permission management system for Laravel applications.
Quick Start
Get up and running in 5 minutes:
Upgrading from an older version? Check the Upgrade Guide for detailed migration instructions.
1. Install via Composer
2. Publish and run migrations
3. Setup your User model
4. Create your first role and permission
5. Protect your routes
Features
- Modern PHP & Laravel - Built for PHP 8.2+ and Laravel 12/13
- Flexible Permission System - Users can have permissions via roles
- Wildcard Permissions - Use
posts.*to match all post-related permissions - Real-Time Gate Integration - A single
Gate::beforehook resolves permissions and roles live; native@can,@canany,@cannotsupport with no stale definitions - Middleware Protection -
role,permission, androle_or_permissionmiddleware - Blade Directives -
@role,@hasrole,@hasanyrole,@hasallroles - Type-Safe Enums - IDE-friendly
PermissionTypeenum - Protected Roles - Protected roles cannot be deleted; attempts throw
ProtectedRoleException - Permission Groups - Organize permissions by resource
- Interactive Commands - Laravel Prompts for creating roles/permissions
- Clean Architecture - Separated concerns with traits and contracts
- Developer Tools - Pint, Pest, Rector, and Larastan included
Support & Sponsorship
Building and maintaining high-quality open-source packages takes hundreds of hours of dedicated time. If you use Custodian in your commercial applications or it saves you significant development time, please consider supporting the project.
Sponsor the Project Ensure the package stays actively maintained, receives rapid bug fixes, and continuous feature updates by becoming a monthly sponsor.
Table of Contents
- Installation
- Upgrade Guide
- Configuration
- Usage
- User Setup
- Creating Roles
- Creating Permissions
- Wildcard Permissions
- Role Management
- Permission Management
- Checking Access
- Middleware
- Gate Integration
- Blade Directives
- Artisan Commands
- Query Scopes
- Models Reference
- Exceptions
- Events
- Performance
- Database Structure
- Enums
- Development
- Troubleshooting
- FAQ
Installation
Requirements
- PHP: 8.2, 8.3, 8.4, or 8.5
- Laravel: 12.x or 13.x
- Database: MySQL 5.7+, PostgreSQL 9.6+, SQLite 3.8+, or SQL Server 2017+
Step 1: Install via Composer
Step 2: Publish and Run Migrations
This creates 4 tables:
roles- Role definitionspermissions- Permission definitionspermission_role- Role-permission relationshipsrole_user- User-role relationships Pivot table names are derived from model table names; the defaults shown above are used unless you customize model tables.
Step 3: Configure User Model
Step 4: (Optional) Publish Config
Configuration
The config/custodian.php file:
Custom Models
To extend or replace the default models, point the config at your own classes — all relations, commands, and gate checks resolve them from the config:
Pivot table names are derived automatically from the models' table names.
Usage
User Setup
Add the Roleable contract and trait to your user model:
Notes:
Roleabletrait on the user model handles both role and permission checks.- Users do not receive permissions directly.
- Assign permissions to roles, then users inherit them from those roles.
Creating Roles
Roles can also be created via the CLI — see Artisan Commands.
Creating Permissions
Authorization only ever checks name — label, description, and group are display metadata for building admin UIs.
Note that getGroup() and byGroup() derive the group from the permission name prefix (users from users.create), not the stored group column, so the resource.action naming convention gives you grouping for free; the column is available for your own custom queries.
Permissions can also be created via the CLI — see Artisan Commands.
Wildcard Permissions
Wildcard permissions automatically match all sub-permissions:
The is_wildcard boolean is automatically set when the name ends with *.
posts.* matches posts.edit but not the bare posts. A permission named just * matches every permission — a super-admin grant. Wildcards can be disabled entirely via CUSTODIAN_WILDCARD_ENABLED=false.
Role Management
Assigning Roles:
Checking Roles:
Permission Management
Assigning to Roles:
Checking Role Permissions:
Checking User Permissions:
Checking Access
Role Checking:
Permission Checking:
Middleware
All middleware supports multiple values (requires ANY):
Responses: unauthenticated requests receive 401; authenticated users lacking access receive 403 (via PermissionDeniedException). Middleware aliases can be renamed in the middleware section of the config.
Gate Integration
Custodian registers a single Gate::before hook that resolves any ability as a permission or role at check time. New roles and permissions are usable immediately — no cache to clear, no gates to re-register. When the ability is not granted by Custodian, the hook returns null, so your own Gate::define gates and policies still run as normal:
The hook only handles checks without arguments. A check that passes a model, like $user->can('update', $post) or $this->authorize('posts.edit', $post), goes to your policy or gate. Otherwise a role or permission named update would pass update on every model. To use a Custodian permission inside a policy, call $user->hasPermission('posts.edit') there. The exception is a user with the literal * permission, who passes every check, with or without arguments.
Blade Directives
Custodian provides custom Blade directives for role checking, in addition to Laravel's built-in @can directives. All directives render nothing for guests — no need to wrap them in @auth:
Custom Role Directives:
Built-in Laravel Directives (via Gate integration):
Artisan Commands
Create a Role:
Create a Permission:
Both commands support Laravel Prompts when optional assignment arguments are omitted.
custodian:create-roleprompts for an optional user identifier and accepts a user ID, email, or name. If the email or name matches more than one user, the command fails; use the ID instead.custodian:create-permissionprompts for an optional role identifier and accepts a role ID or role name.
Upgrade helper:
Applies automated code rewrites when upgrading between Custodian versions. There's nothing to upgrade yet on this first release — see the Upgrade Guide.
Diagnose configuration problems:
Checks that the configured role/permission/user models exist and implement the right contracts, that the roles/permissions tables exist, and that the wildcard config is valid — useful right after installing or changing config/custodian.php.
Query Scopes
Models Reference
User Model (via Traits)
**Roleable trait provides:** - `roles()` - BelongsToMany relationship - `assignRole(...$roles)` - Assign one or more roles - `syncRoles(array $roles, bool $detach = true)` - Sync roles - `syncRolesWithoutDetaching(array $roles)` - Sync without detaching - `revokeRole($role)` - Revoke specific role - `revokeRoles()` - Revoke all roles - `getRoleNames()` - Get all role names - `getRoleLabels()` - Get role labels keyed by name - `hasRole($role)` - Check single role - `hasAllRoles(...$roles)` - Check all roles - `hasAnyRole(...$roles)` - Check any role - `getPermissionNames()` - Get permission names inherited from roles - `hasPermission($permission)` - Check permission (by name or model) - `getPermissions()` - Get all permissions inherited from rolesRole Model
**Properties:** - `name` (string, unique) - `label` (string, nullable) - `description` (text, nullable) - `is_protected` (boolean) **Methods:** - `getName()` - Get role name - `isProtectedRole()` - Check if guarded - `getPermissionNames()` - Get assigned permission names - `permissions()` - BelongsToMany to permissions - `users()` - BelongsToMany to users **Scopes:** - `protected()` - Only protected roles - `unprotected()` - Only unprotected rolesPermission Model
**Properties:** - `name` (string, unique) - `label` (string, nullable) - `description` (text, nullable) - `group` (string, nullable, indexed) - `is_wildcard` (boolean, auto-set) **Methods:** - `getName()` - Get permission name - `getLabel()` - Get human-readable label - `getDescription()` - Get description - `isWildcard()` - Check if wildcard pattern - `getGroup()` - Get resource group (e.g., 'users') - `getType()` - Get PermissionType enum from the name's last segment (null if not a known action) - `roles()` - BelongsToMany to roles **Scopes:** - `wildcard()` - Only wildcard permissions - `byGroup($group)` - Filter by groupCustodian Facade
Utility helpers used internally to derive table names — available if you need the same conventions (e.g. in your own migrations): Both models also expose `getTable()`, which resolves the table name from `config('custodian.tables.*')`.Exceptions
is_protected only blocks deletion. A protected role can still be renamed, have its permissions changed, or have is_protected set back to false and then be deleted.
Protection runs in the model's deleting event, so it only covers $role->delete(). A bulk query such as Role::query()->where(...)->delete() or a raw DB delete skips it. Deleting a role also removes it from every user, because the pivot table cascades. A model delete ($role->delete()) dispatches RoleRevoked for each of those users (loaded in chunks, so widely held roles are safe to delete) and one PermissionRevoked listing the role's permission IDs. Deleting a permission dispatches PermissionRevoked for each role that held it. Bulk and raw deletes dispatch nothing.
Role and Permission allow mass assignment of every column, including is_protected. Don't pass request input straight to Role::create($request->all()) or update(); pick the fields you accept with $request->only([...]) or $request->validated().
A user's permissions are cached on the model instance. If you change a role's permissions with $role->givePermissionTo() and so on, users you have already loaded keep the old permissions until you call $user->refresh() or load them again.
Role and permission mutators (assignRole, givePermissionTo, syncRoles, revokeRole, ...) throw Illuminate\Database\Eloquent\ModelNotFoundException when a name does not resolve to an existing model — typos fail loudly instead of silently doing nothing.
Events
Every role/permission mutation dispatches an event, so you can hook your own audit logging, notifications, or cache invalidation without the package imposing a schema on you:
All four events implement ShouldDispatchAfterCommit: inside a database transaction they fire only once it commits, and never if it rolls back.
The ID arrays list only what actually changed: an assign or sync that attaches nothing dispatches no RoleAssigned/PermissionGranted, and revoking something that was not assigned dispatches nothing.
Performance
Permission checks are memoized per model instance, so repeated hasPermission() calls within a request hit the database once. Role checks use the loaded roles relation, which Custodian refreshes automatically after any role mutation.
Database Structure
Roles Table
Permissions Table
Permission-Role Pivot
Role-User Pivot
Enums
PermissionType
Development
Code Quality Tools
Troubleshooting
Common Issues
Class 'AmdadulHaq\Custodian\Concerns\Roleable' not found
Solution:Target class [role] does not exist.
Solution:Permissions not being recognized
Permissions are resolved live from the database — make sure the permission exists, is assigned to one of the user's roles, and that you're checking a fresh model instance (`$user->fresh()`) if roles were changed on a different instance.Performance Tips
- Use wildcard permissions to reduce permission count
-
Filter at database level instead of loading all users:
- Eager load when needed:
FAQ
Can I use this with Laravel Sanctum?
Yes! Custodian works seamlessly with Sanctum and any auth system.Can users have permissions without roles?
No, users receive permissions via roles.How do wildcard permissions work?
Create a permission like `posts.*` and it automatically matches `posts.create`, `posts.edit`, etc.Can I customize table names?
Yes, publish the config and modify the `tables` section.Does it work with multiple guards?
Yes, it integrates with Laravel's authorization system.Is there a UI for managing roles?
Custodian is backend-only. For a UI, consider Filament Shield or build your own.What Blade directives does Custodian provide?
Custodian ships with `@role`, `@hasrole`, `@hasanyrole`, and `@hasallroles`. Laravel's built-in `@can`, `@canany`, and `@cannot` also work through Gate integration.Can permissions be assigned to permissions?
No, permissions are assigned to roles.Contributing
We welcome contributions! Please see CONTRIBUTING for details.
Changelog
See CHANGELOG for recent changes.
Security
Please review our security policy for reporting vulnerabilities.
Credits
License
The MIT License (MIT). See License File for details.
Made with ❤️ for the Laravel community
All versions of custodian-laravel with dependencies
illuminate/contracts Version ^11.0|^12.0|^13.0
illuminate/database Version ^11.0|^12.0|^13.0
illuminate/support Version ^11.0|^12.0|^13.0