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

Role Provider Array Bundle Laravel Package

dcs/role-provider-array-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies

    composer require dcs/role-provider-array-bundle "~1.0@dev"
    composer require dcs/role-core-bundle "~1.0@dev"  # Required dependency
    
  2. Enable Bundles Add to config/bundles.php (or AppKernel.php for older Laravel versions):

    DCS\Role\Provider\ArrayBundle\DCSRoleProviderArrayBundle::class => ['all' => true],
    DCS\Role\CoreBundle\DCSRoleCoreBundle::class => ['all' => true],
    
  3. Configure Roles Define roles in config/packages/dcs_role_provider_array.yaml (or config/dcs_role_provider_array.php):

    dcs_role_provider_array:
        roles:
            - ROLE_ADMIN
            - ROLE_EDITOR
            - ROLE_USER
    
  4. Extend User Model Use the UserRoleArray trait in your User model:

    use DCS\Role\Provider\ArrayBundle\Model\UserRoleArray;
    
    class User extends Authenticatable
    {
        use UserRoleArray;
    }
    
  5. First Use Case Assign roles to a user:

    $user = User::find(1);
    $user->assignRole('ROLE_ADMIN');  // Assign single role
    $user->assignRoles(['ROLE_EDITOR', 'ROLE_USER']);  // Assign multiple roles
    

Implementation Patterns

Role Management Workflows

  1. Role Assignment

    // Single role
    $user->assignRole('ROLE_ADMIN');
    
    // Multiple roles
    $user->assignRoles(['ROLE_EDITOR', 'ROLE_USER']);
    
    // Remove roles
    $user->removeRole('ROLE_USER');
    $user->removeRoles(['ROLE_EDITOR', 'ROLE_ADMIN']);
    
  2. Role Checking

    if ($user->hasRole('ROLE_ADMIN')) {
        // Admin-specific logic
    }
    
    if ($user->hasAnyRole(['ROLE_ADMIN', 'ROLE_EDITOR'])) {
        // Elevated access logic
    }
    
  3. Role Hierarchy (if needed) Extend the trait or override methods to enforce hierarchy (e.g., ROLE_ADMIN implies ROLE_USER).

Integration with Laravel Features

  1. Policy Integration

    use Illuminate\Auth\Access\HandlesAuthorization;
    
    class PostPolicy
    {
        use HandlesAuthorization;
    
        public function edit(User $user, Post $post)
        {
            return $user->hasAnyRole(['ROLE_ADMIN', 'ROLE_EDITOR']);
        }
    }
    
  2. Middleware for Role-Based Access

    namespace App\Http\Middleware;
    
    use Closure;
    use DCS\Role\Provider\ArrayBundle\Model\UserRoleArray;
    
    class RoleMiddleware
    {
        public function handle($request, Closure $next, ...$roles)
        {
            if (!auth()->user() || !auth()->user()->hasAnyRole($roles)) {
                abort(403);
            }
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $routeMiddleware = [
        'role' => \App\Http\Middleware\RoleMiddleware::class,
    ];
    

    Usage in routes:

    Route::get('/admin', function () {})->middleware('role:ROLE_ADMIN');
    
  3. Dynamic Role Configuration Override the getRoles() method in your User model to fetch roles from a database or API:

    public function getRoles(): array
    {
        return $this->roles->pluck('name')->toArray(); // Example for Eloquent relationship
    }
    

Gotchas and Tips

Pitfalls

  1. Missing Core Bundle Forgetting to install dcs/role-core-bundle will cause runtime errors. Always install both packages.

  2. Case Sensitivity Role names are case-sensitive by default. Ensure consistency (e.g., always use ROLE_ADMIN in uppercase).

  3. Trait Overrides If extending the UserRoleArray trait, avoid naming conflicts with existing methods (e.g., getRoles()).

  4. Configuration Overrides The bundle expects roles to be defined in config/packages/dcs_role_provider_array.yaml. If using PHP config, ensure the key matches:

    'dcs_role_provider_array' => [
        'roles' => ['ROLE_ADMIN', 'ROLE_USER'],
    ],
    
  5. Caching Roles The trait may cache role assignments. Clear cache if roles change dynamically:

    $user->clearRolesCache();
    

Debugging Tips

  1. Check Role Assignment Dump roles to debug:

    dd(auth()->user()->getRoles());
    
  2. Validate Configuration Ensure no typos in role names or config keys. Use:

    php bin/console debug:config dcs_role_provider_array
    
  3. Override Methods for Custom Logic If the default behavior is insufficient, override methods like:

    public function hasRole($role)
    {
        // Custom logic (e.g., check role hierarchy)
        return parent::hasRole($role) || $this->isAdmin();
    }
    

Extension Points

  1. Custom Role Provider Implement DCS\Role\CoreBundle\Provider\RoleProviderInterface for non-array-based role storage (e.g., database).

  2. Event Listeners Listen for role changes to trigger side effects (e.g., log role assignments):

    use DCS\Role\CoreBundle\Event\RoleAssignedEvent;
    
    public function onRoleAssigned(RoleAssignedEvent $event)
    {
        Log::info('Role assigned', ['user' => $event->getUser(), 'role' => $event->getRole()]);
    }
    

    Register in EventServiceProvider:

    protected $listen = [
        RoleAssignedEvent::class => [
            YourListener::class,
        ],
    ];
    
  3. Localization Extend the bundle to support localized role names by overriding the getRoleLabel() method in the trait.

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui