Download the PHP package amdadulhaq/guard-laravel without Composer
On this page you can find all versions of the php package amdadulhaq/guard-laravel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download amdadulhaq/guard-laravel
More information about amdadulhaq/guard-laravel
Files in amdadulhaq/guard-laravel
Package guard-laravel
Short Description Guard is a role and permission management system for Laravel
License MIT
Homepage https://github.com/amdad121/guard-laravel
Informations about the package guard-laravel
Guard - Modern Role & Permission Management for Laravel
[!IMPORTANT] This package is being renamed to avoid confusion with Laravel's own
Guard/Gateterminology. Future development moves to custodian-laravel — same API, new name. New projects should start there; existing projects onguard-laravelkeep working and can migrate later.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 11/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 - Guarded Roles - Guarded roles cannot be deleted; attempts throw
GuardedRoleException - 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 Guard 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
- Performance
- Database Structure
- Enums
- Development
- Troubleshooting
- FAQ
Installation
Requirements
- PHP: 8.2, 8.3, 8.4, or 8.5
- Laravel: 11.x, 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/guard.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 *.
A permission named just * matches every permission — a super-admin grant. Wildcards can be disabled entirely via GUARD_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
Guard 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 Guard, the hook returns null, so your own Gate::define gates and policies still run as normal:
Blade Directives
Guard 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.
guard:create-roleprompts for an optional user identifier and accepts a user ID, email, or name.guard:create-permissionprompts for an optional role identifier and accepts a role ID or role name.
Upgrade helper:
Rewrites your application code from older Guard versions to the current architecture — updates v1/v2 trait and contract usage in app/Models, removes API calls deleted in v3, cleans the published config, and publishes any pending schema upgrade migrations. See the Upgrade Guide for details.
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_guarded` (boolean) **Methods:** - `getName()` - Get role name - `isProtectedRole()` - Check if guarded - `getPermissionNames()` - Get assigned permission names - `permissions()` - BelongsToMany to permissions - `users()` - BelongsToMany to users **Scopes:** - `guarded()` - Only guarded roles - `unguarded()` - Only unguarded 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 groupGuard 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('guard.tables.*')`.Exceptions
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.
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 Guard 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\Guard\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! Guard 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?
Guard is backend-only. For a UI, consider Filament Shield or build your own.What Blade directives does Guard provide?
Guard 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.
Star History
If Guard helps you, a star helps the project grow.
Credits
License
The MIT License (MIT). See License File for details.
Made with ❤️ for the Laravel community
All versions of guard-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