santigarcor/laratrust
Laratrust adds role and permission management to Laravel with support for multiple user models, teams, guards, caching, events, middleware, gates/policies, and an optional admin panel for managing roles and permissions.
Install via Composer: composer require santigarcor/laratrust. Run php artisan vendor:publish --provider="Laratrust\LaratrustServiceProvider" to publish config and migrations. Set teams.enabled in config/laratrust.php if needed, then run php artisan laratrust:setup (or laratrust:setup-teams). Run migrations and begin defining roles/permissions in seeders or tinker:
Role::create(['name' => 'admin']);
Permission::create(['name' => 'edit-posts']);
$user->attachRole('admin');
$user->attachPermission('edit-posts');
Start by checking permissions in controllers using $user->isAbleTo('edit-posts') or middleware ('permission:edit-posts'). The laratrust-seed command generates default admin role and permissions if configured.
Use dedicated Role and Permission model classes extending LaratrustRole/LaratrustPermission for extensibility. Seed roles/permissions once via database seeders—never hardcode in controllers. Leverage middleware in routes: Route::middleware('role:admin')->group(...). Use Laratrust::hasRole()/isAbleTo() for guest/anonymous context. Use syncRoles()/syncPermissions() when bulk-updating user access, attach() for incremental changes. Integrate with Laravel Gates by registering in AuthServiceProvider:
Gate::before(fn ($user) => $user->isAbleTo('super-admin') ? true : null);
For policies, grant permissions via Laratrust::ability() and let policies handle entity-specific logic. In teams mode, use teamRoles(), teamPermissions(), and scope checks with hasTeamRole().
Avoid using the deprecated can() method—it conflicts with Laravel’s core capabilities. Always clear config cache after changing config/laratrust.php (php artisan config:clear). Roles/permissions are cached by default; invalidate via Laratrust::flushPermissions() or Laratrust::flushRoles() after dynamic changes. Remember polymorphic relationships (role_user, permission_user) require nullable user_type and user_id. When using teams, ensure all User model relationships include teams() and teamRoles() methods. If using custom guards, configure guards array in config and assign roles/permissions per guard via guardName() calls. Watch for false positives with pipe-separated checks—e.g., hasRole('owner|admin') returns true if either is present unless strict mode (true, second arg) is used. Extend via events: RoleCreated, PermissionAttached, etc., or tap into middleware to log permission denials.
How can I help you explore Laravel packages today?