Skip to content

Conversation

@imhayatunnabi
Copy link
Contributor

I was working on a multi-tenant inventory which has multiple roles and permissions where we decided to modernize our codebase by migrating from string-based permissions to PHP 8.1+ BackedEnums for better type safety and IDE autocompletion. We created a comprehensive enum structure:

enum Permission: string
{
    case VIEW_DASHBOARD = 'view dashboard';
    case EDIT_ARTICLES = 'edit articles';
    case DELETE_ARTICLES = 'delete articles';
    case MANAGE_USERS = 'manage users';
    case PUBLISH_CONTENT = 'publish content';
}

enum Role: string
{
    case ADMIN = 'admin';
    case EDITOR = 'editor';
    case WRITER = 'writer';
}

Everything was going smoothly - we updated our routes to use enums with PermissionMiddleware and RoleMiddleware, and they worked perfectly:

// This worked great
Route::middleware(['permission:'.Permission::EDIT_ARTICLES->value])
    ->group(function () {
        // ...
    });

// This also worked
Route::middleware([PermissionMiddleware::using(Permission::EDIT_ARTICLES)])
    ->group(function () {
        // ...
    });

Then the problem hit: We had several routes that needed to check for either a role or a permission (e.g., "allow access if user is an admin OR has edit permission"). We tried to use RoleOrPermissionMiddleware with our enums:

// This failed silently - the middleware didn't recognize the enum
Route::middleware([
    RoleOrPermissionMiddleware::using(Permission::EDIT_ARTICLES)
])->group(function () {
    // Users were getting 403 errors even when they had the permission!
});

Here I have added complete BackedEnum which is a PHP built-in interface in PHP 8.1+ versions to support to RoleOrPermissionMiddleware, making it consistent with the other middleware classes in the package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant