Ladder for Laravel

repository·main·Indexed 42 days ago

https://github.com/eneadm/ladder

A Laravel package for role and permission management that uses a static approach to reduce database queries. It allows developers to define roles and permissions in code via the LadderServiceProvider and provides the HasRoles trait for User models. Features include wildcard permissions, a visual roles and permissions matrix via the ladder:show command, and support for Laravel 12+.

Tokens
2.7K
Snippets
19
Records
20
Agent score
53%

What's inside Ladder

  1. Use Wildcard Permissions

    main

    Ladder supports wildcard patterns to grant broad access:

    • *: Grants access to all permissions.
    • *:create: Grants access to all 'create' permissions (e.g., post:create, user:create).
    • *:update: Grants access to all 'update' permissions (e.g., post:update, user:update).
    Ladder::role('super-admin', 'Super Administrator', [
        '*', // Full access to everything
    ])->description('Super Administrator users can perform any action.');
    
    Ladder::role('content-manager', 'Content Manager', [
        '*:create', // Can create any resource
        '*:update', // Can update any resource
        'post:read',
    ])->description('Content Manager users can create and update any content.');
  2. Integrate HasRoles trait into User model

    main

    To enable role and permission management on your User model, add the Ladder\HasRoles trait to App\Models\User.

    use Ladder\HasRoles;
    
    class User extends Authenticatable
    {
        use HasRoles;
    }
  3. Authorize users using permissions

    main

    When performing request authorization (e.g., in Laravel Policies), it is recommended to check for granular permissions using hasPermission() rather than checking for roles. Roles should primarily be used for UI presentation.

    /**
     * Determine whether the user can update a post.
     */
    public function update(User $user, Post $post): bool
    {
        return $user->hasPermission('post:update');
    }
  4. Install Ladder

    main

    To install Ladder in your Laravel project (requires Laravel 12+), follow these steps:

    1. Install the package via Composer:
      composer require eneadm/ladder
    2. Initialize the Ladder service provider:
      php artisan ladder:install
    3. Run migrations to create the user_role pivot table:
      php artisan migrate
    composer require eneadm/ladder
    php artisan ladder:install
    php artisan migrate
  5. Install Ladder scaffolding via CLI

    main

    Run the ladder:install command to set up the Ladder scaffolding in your Laravel application. This command performs the following actions:

    1. Creates the App\Providers\LadderServiceProvider.php file by copying it from the package stubs into your application's app/Providers directory.
    2. Automatically registers the LadderServiceProvider in your config/app.php file, ensuring it is loaded after the RouteServiceProvider.
    php artisan ladder:install
  6. Assign Roles to Users

    main

    Assign roles to a user by interacting with the roles relationship provided by the HasRoles trait. Use updateOrCreate to ensure the role is assigned without duplicates.

    use App\Models\User;
    
    $user = User::find(1);
    
    $user->roles()->updateOrCreate(['role' => 'admin']);
  7. Define Roles and Permissions in LadderServiceProvider

    main

    Roles and their associated permissions are defined statically in App\Providers\LadderServiceProvider using the Ladder::role method. You specify a slug, a display name, an array of permissions, and an optional description.

    Ladder::role('admin', 'Administrator', [
        'post:read',
        'post:create',
        'post:update',
        'post:delete',
    ])->description('Administrator users can perform any action.');
    
    Ladder::role('editor', 'Editor', [
        'post:read',
        'post:create',
        'post:update',
    ])->description('Editor users have the ability to read, create, and update posts.');
  8. Use HasRoles methods to manage and check permissions

    main

    The HasRoles trait provides several methods for interacting with roles and permissions. Method arguments can be strings, arrays, Collections, or Enums. For multiple entries, use arrays or Collections for better performance.

    MethodReturn TypeDescription
    $user->rolesCollectionAccess all of the user's roles
    $user->hasRole($role)boolDetermine if the user has the given role
    $user->rolePermissions($role)arrayAccess all permissions for a specific role belonging to the user
    $user->permissions()CollectionAccess all permissions belonging to the user
    $user->hasRolePermission($role, $permission)boolDetermine if a specific role has a given permission
    $user->hasPermission($permission)boolDetermine if the user has a given permission
  9. View Roles and Permissions matrix

    main

    Use the ladder:show Artisan command to display a visual matrix of all roles and their assigned permissions in the terminal. Use the --style argument to change the table appearance.

    # Display the matrix with different styles
    php artisan ladder:show default
    php artisan ladder:show borderless
    php artisan ladder:show compact
    php artisan ladder:show box
  10. Define roles and permissions with the Ladder class

    main

    The Ladder class serves as the central registry for roles and permissions in the application. You can use it to define roles by providing a unique key, a display name, and an array of associated permissions. When a role is defined via Ladder::role(), the permissions are automatically merged into a global registry of unique, sorted permissions.

    use Ladder\Ladder;
    
    // Define a role with specific permissions
    Ladder::role('admin', 'Administrator', ['edit_posts', 'delete_posts', 'manage_users']);
    
    // Retrieve the role object
    $adminRole = Ladder::findRole('admin');
  11. Serialize a Role to JSON

    main

    The Role class implements JsonSerializable. When converted to JSON, the name and description fields are passed through the __() translation function. The resulting JSON structure contains the following keys:

    • key: The unique identifier of the role.
    • name: The translated display name.
    • description: The translated description.
    • permissions: The array of permission strings.
    $role = new Role('admin', 'Administrator', ['*']);
    $role->description('Full access');
    
    echo json_encode($role);
    // Output: {"key":"admin","name":"Administrator","description":"Full access","permissions":["*"]}