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

Permission Bundle Laravel Package

eddmash/permission-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require eddmash/permission-bundle
    

    Add to config/bundles.php (Symfony) or config/app.php (Laravel wrapper if available):

    return [
        // ...
        Eddmash\PermissionBundle\PermissionBundle::class => ['all' => true],
    ];
    
  2. Publish Configuration

    php artisan vendor:publish --provider="Eddmash\PermissionBundle\PermissionBundle" --tag="config"
    

    Locate the config file at config/permission.php and adjust as needed.

  3. First Use Case: Assigning a Role

    use Eddmash\PermissionBundle\Entity\Role;
    
    $adminRole = $roleRepository->findOneBy(['name' => 'ROLE_ADMIN']);
    $user->addRole($adminRole);
    $entityManager->persist($user);
    $entityManager->flush();
    
  4. Check Permissions in Controller

    use Symfony\Component\HttpFoundation\Response;
    use Eddmash\PermissionBundle\Annotation\Secure;
    
    class AdminController extends AbstractController
    {
        /**
        * @Secure("ROLE_ADMIN")
        */
        public function dashboard(): Response
        {
            return new Response('Admin Dashboard');
        }
    }
    

Implementation Patterns

Role-Based Access Control (RBAC) Workflow

  1. Define Roles Extend Eddmash\PermissionBundle\Entity\Role or use the provided CRUD interface:

    $role = new Role();
    $role->setName('ROLE_EDITOR');
    $role->setDescription('Can edit content');
    $entityManager->persist($role);
    
  2. Assign Roles to Users

    $user = $userRepository->find($userId);
    $role = $roleRepository->findOneBy(['name' => 'ROLE_EDITOR']);
    $user->addRole($role);
    $entityManager->flush();
    
  3. Check Permissions

    $this->denyAccessUnlessGranted('ROLE_ADMIN', $user);
    // OR via annotation (see above)
    

Integration with Doctrine

  • Custom Entities: Extend Eddmash\PermissionBundle\Entity\User or Role to add fields.
  • Repositories: Use UserRepository and RoleRepository for queries:
    $usersWithRole = $userRepository->findByRole('ROLE_ADMIN');
    

Voter Integration

Create a custom voter for granular permissions:

use Eddmash\PermissionBundle\Security\Voter\PermissionVoter;

class PostVoter extends PermissionVoter
{
    protected function supports(string $attribute, $subject): bool
    {
        return $attribute === 'EDIT_POST';
    }

    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
    {
        return $token->getUser()->hasRole('ROLE_EDITOR');
    }
}

Register the voter in security.yaml:

security:
    access_control:
        - { path: ^/admin/posts, roles: ROLE_EDITOR, voter: post_voter }

Gotchas and Tips

Common Pitfalls

  1. Annotation Not Working? Ensure the bundle is enabled in bundles.php and the annotation listener is registered. For Laravel, check if the Symfony bridge is properly set up.

  2. Permission Caching Issues Clear Symfony’s cache after role changes:

    php artisan cache:clear
    
  3. Doctrine ORM Mismatch The bundle assumes Doctrine ORM. If using Eloquent, wrap the bundle in a service layer or use a hybrid approach.

  4. Role Hierarchy Not Enforced The bundle does not natively support role inheritance (e.g., ROLE_ADMIN implies ROLE_USER). Implement a custom RoleHierarchy voter or use a library like Stof/DoctrineExtensions.

Debugging Tips

  • Check User Roles
    dump($user->getRoles()); // ArrayCollection of Role objects
    
  • Enable Debugging Set debug: true in config/permission.php to log permission checks.

Extension Points

  1. Custom Role Fields Override the Role entity and update the bundle’s mapping:

    # config/doctrine/Role.orm.yml
    Eddmash\PermissionBundle\Entity\Role:
        fields:
            customField:
                type: string
    
  2. Event Listeners Hook into role/user events (e.g., RolePrePersist):

    use Eddmash\PermissionBundle\Event\RoleEvents;
    
    $eventDispatcher->addListener(RoleEvents::PRE_PERSIST, function ($event) {
        $role = $event->getRole();
        $role->setCreatedAt(new \DateTime());
    });
    
  3. API Integration Use the bundle with API Platform or NelmioApiDoc to secure endpoints:

    # config/api_platform/resources.yaml
    resources:
        App\Entity\Post:
            properties:
                owner: ~
            security: "is_granted('ROLE_EDITOR')"
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor