dcs/role-provider-array-bundle
Install Dependencies
composer require dcs/role-provider-array-bundle "~1.0@dev"
composer require dcs/role-core-bundle "~1.0@dev" # Required dependency
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],
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
Extend User Model
Use the UserRoleArray trait in your User model:
use DCS\Role\Provider\ArrayBundle\Model\UserRoleArray;
class User extends Authenticatable
{
use UserRoleArray;
}
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
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']);
Role Checking
if ($user->hasRole('ROLE_ADMIN')) {
// Admin-specific logic
}
if ($user->hasAnyRole(['ROLE_ADMIN', 'ROLE_EDITOR'])) {
// Elevated access logic
}
Role Hierarchy (if needed)
Extend the trait or override methods to enforce hierarchy (e.g., ROLE_ADMIN implies ROLE_USER).
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']);
}
}
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');
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
}
Missing Core Bundle
Forgetting to install dcs/role-core-bundle will cause runtime errors. Always install both packages.
Case Sensitivity
Role names are case-sensitive by default. Ensure consistency (e.g., always use ROLE_ADMIN in uppercase).
Trait Overrides
If extending the UserRoleArray trait, avoid naming conflicts with existing methods (e.g., getRoles()).
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'],
],
Caching Roles The trait may cache role assignments. Clear cache if roles change dynamically:
$user->clearRolesCache();
Check Role Assignment Dump roles to debug:
dd(auth()->user()->getRoles());
Validate Configuration Ensure no typos in role names or config keys. Use:
php bin/console debug:config dcs_role_provider_array
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();
}
Custom Role Provider
Implement DCS\Role\CoreBundle\Provider\RoleProviderInterface for non-array-based role storage (e.g., database).
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,
],
];
Localization
Extend the bundle to support localized role names by overriding the getRoleLabel() method in the trait.
How can I help you explore Laravel packages today?