Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Permission Laravel Package

spatie/laravel-permission

Database-backed roles and permissions for Laravel. Assign roles and permissions to users, sync them to the Gate, and check abilities with Laravel’s built-in can()/authorize features. Includes migrations, caching, teams, and flexible model setup.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Role-Based Access Control (RBAC) Alignment: The package aligns perfectly with Laravel’s built-in authorization system (Gates/Policies) and integrates seamlessly with Eloquent models. It extends Laravel’s native can() method, reducing friction for developers already familiar with Laravel’s authorization patterns.
  • Modular Design: The package follows Laravel’s conventions (Service Providers, Facades, Traits) and is designed to be non-intrusive. It does not enforce a monolithic architecture, allowing teams to adopt it incrementally (e.g., start with permissions-only, then add roles).
  • Event-Driven Extensibility: Supports custom events (e.g., RoleAssigned, PermissionRevoked) for auditing, logging, or triggering side effects (e.g., Slack notifications). This enables observability and integration with other systems.
  • Wildcard Permissions: Supports pattern-matching permissions (e.g., edit-*), which is useful for broad access control (e.g., "edit all resources in a namespace") while maintaining granularity.

Integration Feasibility

  • Laravel Ecosystem Compatibility: Officially supports Laravel 12+ (PHP 8.3+) and integrates with core features like:
    • Eloquent models (via HasRoles, HasPermissions traits).
    • Gates/Policies (permissions are registered as Gates by default).
    • API resources (e.g., PermissionResource, RoleResource).
    • Artisan commands for management (e.g., permission:create-role).
  • Database Agnostic: Works with any database supported by Laravel (MySQL, PostgreSQL, SQLite, etc.). Migrations are provided for roles, permissions, and model_has_permissions/model_has_roles tables.
  • Team Support: Optional "teams" feature (enabled via config) for hierarchical permissions (e.g., team-wide roles). Useful for SaaS/multi-tenant applications.
  • Caching: Supports caching permissions/roles to improve performance in high-traffic applications (e.g., spatie/laravel-caching).

Technical Risk

  • Migration Complexity:
    • Schema Changes: Requires 4+ tables (roles, permissions, model_has_permissions, model_has_roles). For existing applications, this may require downtime or a phased migration strategy.
    • Data Migration: If transitioning from a custom RBAC system, mapping legacy permissions/roles to the new schema could be error-prone. The package provides migration helpers but may need customization.
  • Performance at Scale:
    • N+1 Queries: The can() method triggers a query per permission check by default. Mitigated by:
      • Caching (enabled via config).
      • Eager-loading permissions/roles in policies (with(['roles', 'permissions'])).
      • Using Gate::before() hooks for bulk checks.
    • Wildcard Overhead: Wildcard permissions (e.g., edit-*) add complexity to permission resolution. Test thoroughly in production-like environments.
  • Version Lock-In:
    • Breaking Changes: v7+ dropped PHP 8.3 support (as of v7.3.0) and introduced type safety. Ensure your team’s PHP/Laravel version aligns with the package’s requirements.
    • Laravel 13+: While the package supports L13, some features (e.g., Passport) may lag behind Laravel’s latest releases. Monitor the changelog for compatibility notes.
  • Customization Limits:
    • Hardcoded Logic: Some methods (e.g., syncPermissions) are opinionated. Extending core behavior may require overriding traits or writing decorators.
    • Teams Feature: The teams feature is opt-in and may require additional configuration for complex hierarchies (e.g., nested teams).

Key Questions

  1. Current RBAC Implementation:
    • Does the application already use a custom RBAC system? If so, what’s the effort to migrate data and logic to spatie/laravel-permission?
    • Are there existing Gates/Policies that need to be updated to use the new permission system?
  2. Performance Requirements:
    • What’s the expected scale (e.g., users, permission checks per second)? Will caching or Octane (Laravel’s server) be needed?
    • Are wildcard permissions required, or can explicit permissions suffice?
  3. Teams Feature:
    • Is team-based access control needed? If so, how complex are the team hierarchies (e.g., nested teams, dynamic membership)?
  4. Auditability:
    • Are permission changes (e.g., role assignments) audited? If so, how will events (e.g., RoleAssigned) be logged?
  5. Testing Strategy:
    • How will permission logic be tested? The package provides Pest tests, but application-specific permission flows may need custom test doubles.
  6. Deployment Strategy:
    • Can the package be deployed in a feature flagged manner (e.g., behind a toggle) to mitigate migration risk?
    • Are there rollback plans if the migration fails or performance issues arise?

Integration Approach

Stack Fit

  • Laravel Core: The package is a first-class citizen in the Laravel ecosystem, leveraging:
    • Service Providers: Registers itself via Spatie\Permission\PermissionServiceProvider.
    • Facades: Provides Gate, Permission, and Role facades for fluent syntax.
    • Artisan Commands: CLI tools for managing roles/permissions (e.g., permission:create-role).
    • Policies/Gates: Permissions are registered as Gates, enabling seamless integration with Laravel’s authorization system.
  • Database Layer:
    • Uses Eloquent models (Role, Permission) with polymorphic relationships to user models.
    • Supports custom table names via config (permission.table_names).
  • API/HTTP:
    • Includes API resources for roles/permissions (e.g., RoleResource).
    • Provides middleware (RoleOrPermissionMiddleware) for route-based access control.
  • Testing:
    • Compatible with Laravel’s testing tools (e.g., actingAs() with permissions).
    • Pest test suite included (can be extended for application-specific tests).

Migration Path

  1. Pre-Integration:
    • Assess Current State: Document existing RBAC logic (custom tables, Gates, Policies).
    • Version Alignment: Ensure Laravel/PHP versions meet the package’s requirements (e.g., PHP 8.3+ for v7.3.0+).
    • Backup Data: Export existing permissions/roles for validation post-migration.
  2. Installation:
    • Composer: composer require spatie/laravel-permission.
    • Publish Config: php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider".
    • Run Migrations: php artisan migrate (creates roles, permissions, and pivot tables).
  3. Data Migration:
    • Option 1: Manual mapping of legacy data to new tables (use Role::create() and Permission::create()).
    • Option 2: Write a custom migration script to transform data (e.g., using Eloquent or raw SQL).
    • Validation: Verify data integrity (e.g., count roles/permissions, test sample users).
  4. Code Integration:
    • Replace Custom Logic: Swap custom RBAC checks with spatie/laravel-permission methods (e.g., $user->givePermissionTo('edit')).
    • Update Policies/Gates: Modify Gates to use the new permission system (e.g., Gate::define('edit', fn($user) => $user->can('edit'))).
    • Middleware: Replace custom middleware with RoleOrPermissionMiddleware (e.g., auth:adminrole:admin).
  5. Testing:
    • Unit Tests: Verify permission checks (e.g., assertTrue($user->can('edit'))).
    • Integration Tests: Test role/permission assignments and edge cases (e.g., wildcard conflicts).
    • Performance Tests: Load-test permission resolution (especially with caching).
  6. Post-Migration:
    • Deprecate Old Code: Remove or flag legacy RBAC logic.
    • Monitor: Track permission-related errors/logs (e.g., PermissionDoesNotExistException).

Compatibility

  • Laravel Versions:
    • v7.x: Laravel 12+ (PHP 8.3+).
    • v6.x: Laravel 9/10/11 (PHP 8.0+).
    • Check the upgrade guide for version-specific notes.
  • PHP Extensions:
    • No additional extensions required beyond Laravel’s defaults.
  • Third-Party Packages:
    • Conflicts: Avoid naming collisions (e.g., custom Permission models). Use the package’s config to override table/column names.
    • Dependencies: Ensure compatibility with other Spatie packages (e.g., laravel-activitylog) if used.
  • Custom Models:
    • The package works with any Eloquent model. Use the HasRoles/HasPermissions traits:
      use Spatie\Permission\Traits\HasRoles;
      class User extends Authenticatable {
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony