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

Users Groups Laravel Package

baks-dev/users-groups

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require baks-dev/users-groups
   php artisan vendor:publish --provider="BaksDev\UsersGroups\UsersGroupsServiceProvider" --tag="migrations"
   php artisan migrate
  • Run the asset installer if needed (e.g., for admin panel resources):
    php artisan baks:assets:install
    
  1. First Use Case:

    • Create a Role:
      use BaksDev\UsersGroups\Entity\Role;
      
      $adminRole = new Role();
      $adminRole->setName('admin');
      $adminRole->setDescription('Full access');
      $em->persist($adminRole);
      $em->flush();
      
    • Assign Role to User:
      $user->addRole($adminRole); // Assuming User entity has `addRole()` method
      $em->flush();
      
  2. Where to Look First:

    • Entities: src/Entity/ (e.g., User.php, Role.php, Group.php).
    • Services: src/Service/ (e.g., RoleService.php, GroupService.php).
    • Doctrine Repositories: src/Repository/ for custom queries.
    • Console Commands: src/Console/ for CLI utilities (e.g., baks:assets:install).

Implementation Patterns

Core Workflows

  1. Role-Based Access Control (RBAC):

    • Check Permissions:
      if ($user->hasRole('admin')) {
          // Grant access
      }
      
    • Dynamic Role Assignment:
      $user->setRoles([$role1, $role2]); // Bulk assignment
      
  2. Group Management:

    • Create a Group with Roles:
      $group = new Group();
      $group->setName('Editors');
      $group->addRole($editorRole);
      $em->persist($group);
      
    • Assign Users to Groups:
      $group->addUser($user);
      $em->flush();
      
  3. Integration with Auth:

    • Extend Laravel’s Auth System:
      // In AuthServiceProvider.php
      public function boot()
      {
          $this->registerPolicies();
          $this->gate()->define('admin-access', function ($user) {
              return $user->hasRole('admin');
          });
      }
      
  4. Middleware for Role Checks:

    namespace App\Http\Middleware;
    
    use Closure;
    use BaksDev\UsersGroups\Entity\UserInterface;
    
    class CheckRole
    {
        public function handle($request, Closure $next, $role)
        {
            if (!$request->user() instanceof UserInterface || !$request->user()->hasRole($role)) {
                abort(403);
            }
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

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

    Usage in routes:

    Route::get('/admin', function () {})->middleware('role:admin');
    
  5. Event Listeners:

    • Listen for role/permission changes:
      // In EventServiceProvider.php
      protected $listen = [
          'BaksDev\UsersGroups\Event\RoleAssigned' => [
              \App\Listeners\LogRoleAssignment::class,
          ],
      ];
      

Best Practices

  • Use Transactions:
    $em->beginTransaction();
    try {
        $user->addRole($role);
        $em->flush();
        $em->commit();
    } catch (\Exception $e) {
        $em->rollBack();
        throw $e;
    }
    
  • Lazy-Loading: Avoid N+1 queries by eager-loading roles/groups:
    $user = $em->getRepository(User::class)->findOneBy(['id' => 1], ['roles' => 'join']);
    
  • Caching: Cache role checks if performance is critical:
    $hasRole = cache()->remember("user_{$user->id}_roles", now()->addHours(1), function () use ($user) {
        return $user->hasRole('admin');
    });
    

Gotchas and Tips

Common Pitfalls

  1. Entity Manager Confusion:

    • Ensure you’re using the correct EntityManager (e.g., Doctrine\ORM\EntityManagerInterface).
    • Fix: Inject EntityManager via constructor or use Doctrine\ORM\EntityManagerInterface from the service container.
  2. Circular Dependencies:

    • If User and Role entities reference each other bidirectionally, configure orphanRemoval and cascade carefully in yaml/xml mappings to avoid stale data.
    • Example:
      # config/doctrine/orm/Entity/User.orm.yml
      ManyToMany:
        roles:
          targetEntity: BaksDev\UsersGroups\Entity\Role
          joinTable:
            name: user_roles
            joinColumns:
              user_id:
                referencedColumnName: id
            inverseJoinColumns:
              role_id:
                referencedColumnName: id
          orphanRemoval: true
          cascade: ["persist"]
      
  3. Migration Conflicts:

    • If you modify the schema after initial migration, run:
      php artisan doctrine:migrations:diff
      php artisan doctrine:migrations:migrate
      
    • Tip: Use --dry-run to preview changes:
      php artisan doctrine:migrations:diff --dry-run
      
  4. Permission Caching:

    • Avoid caching sensitive permission checks (e.g., hasRole('admin')) if roles can change frequently. Use short TTL or invalidate cache on role updates.
  5. Asset Installation:

    • The baks:assets:install command may overwrite existing files. Backup public/ before running it in production.

Debugging Tips

  1. Query Logging: Enable Doctrine logging to debug queries:

    $em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    

    Or use Laravel’s built-in logging:

    \DB::enableQueryLog();
    $em->flush();
    \DB::getQueryLog(); // Inspect queries
    
  2. Event Debugging:

    • Listen for all events temporarily to debug:
      $dispatcher->addListener('*', function ($event) {
          \Log::debug('Event:', [$event->getName(), $event->getSubject()]);
      });
      
  3. Role Assignment Issues:

    • If roles aren’t persisting, check:
      • Bidirectional relationships (e.g., Role entity should have a users collection).
      • Cascade settings in orm.xml/yaml.
      • Transaction boundaries.

Extension Points

  1. Custom Role Strategies:

    • Extend BaksDev\UsersGroups\Service\RoleService to add custom logic (e.g., hierarchical roles):
      class CustomRoleService extends RoleService
      {
          public function hasInheritedRole(UserInterface $user, string $roleName): bool
          {
              // Implement logic for role inheritance
          }
      }
      
    • Bind the service in config/services.php:
      'role_service' => \App\Service\CustomRoleService::class,
      
  2. Custom Groups:

    • Extend the Group entity or create a new entity that implements GroupInterface:
      class TeamGroup implements GroupInterface
      {
          // Custom group logic
      }
      
  3. API Resources:

    • Use Laravel’s API Resources to transform entities for APIs:
      namespace App\Http\Resources;
      
      use BaksDev\UsersGroups\Entity\User;
      use Illuminate\Http\Resources\Json\JsonResource;
      
      class UserResource extends JsonResource
      {
          public function toArray($request)
          {
              return [
                  'id' => $this->id,
                  'roles' => $this->roles->map(fn($role) => $role->getName()),
              ];
          }
      }
      
  4. Testing:

    • Use the provided test group to write focused tests:
      phpunit --group=users-groups
      
    • Example Test:
      public function testUserHasRole()
      {
          $this->markTestSkipped('Example test for role assignment');
          $user = new User();
          $role = new Role();
          $role->setName('test');
          $user->addRole($role);
          $this->assertTrue($user->hasRole('test'));
      }
      

Configuration Quirks

  1. Doctrine Configuration:
    • Ensure BaksDev\UsersGroups\UsersGroupsServiceProvider is registered in config/app.php under `
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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