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

User Bundle Laravel Package

sylius/user-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sylius/user-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Sylius\UserBundle\SyliusUserBundle::class => ['all' => true],
    ];
    
  2. Database Migrations: Run migrations to create the user table:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Use Case: Register a new user via the built-in controller:

    php bin/console sylius:user:create --email=test@example.com --password=password
    

    Or use the REST API (if enabled) with:

    POST /api/users
    
  4. Key Configuration: Check config/packages/sylius_user.yaml for default settings (e.g., security roles, user_class).


Implementation Patterns

Core Workflows

  1. User Registration: Extend the Sylius\UserBundle\Form\Type\RegistrationType or use the default registration form:

    {{ form_start(form) }}
        {{ form_row(form.email) }}
        {{ form_row(form.plainPassword) }}
    {{ form_end(form) }}
    
  2. Authentication: Use Symfony’s security system with Sylius’ User entity:

    # config/packages/security.yaml
    providers:
        sylius_user:
            entity: { class: Sylius\UserBundle\Entity\User }
    
  3. User Management:

    • List users:
      $users = $this->getDoctrine()->getRepository(User::class)->findAll();
      
    • Update user:
      $user->setEmail('new@example.com');
      $em->persist($user);
      $em->flush();
      
  4. API Integration: Enable API platform support (if using api-platform/core):

    # config/packages/api_platform.yaml
    resources:
        Sylius\UserBundle\Entity\User:
            collectionOperations:
                post: { security: "is_granted('ROLE_ADMIN')" }
    
  5. Event-Driven Extensions: Listen to user events (e.g., UserRegisteredEvent):

    // src/EventListener/UserListener.php
    public function onUserRegistered(UserRegisteredEvent $event): void
    {
        $user = $event->getUser();
        // Send welcome email, log activity, etc.
    }
    

    Register in services.yaml:

    services:
        App\EventListener\UserListener:
            tags:
                - { name: kernel.event_listener, event: sylius.user.registered }
    

Integration Tips

  1. Custom User Fields: Extend the User entity:

    // src/Entity/CustomUser.php
    class CustomUser extends User
    {
        #[ORM\Column]
        private ?string $customField = null;
    
        // Getters/setters...
    }
    

    Update sylius_user.yaml:

    user_class: App\Entity\CustomUser
    
  2. Role-Based Access: Use Symfony’s voter system or Sylius’ built-in roles (ROLE_USER, ROLE_ADMIN):

    $user->addRole('ROLE_ADMIN');
    $em->flush();
    
  3. Password Reset: Use the built-in PasswordResetToken entity or integrate with symfonycasts/verify-email:

    php bin/console sylius:user:password-reset-request --email=user@example.com
    
  4. Testing: Use Symfony’s WebTestCase with a test user:

    public function setUp(): void
    {
        $this->client->loginUser($this->createTestUser());
    }
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • If extending the User entity, run migrations after schema updates:
      php bin/console doctrine:schema:update --force
      
    • Avoid modifying the id, username, or email fields directly (use accessors).
  2. Security Misconfigurations:

    • Ensure ROLE_USER is required for protected routes:
      # config/packages/security.yaml
      access_control:
          - { path: ^/account, roles: ROLE_USER }
      
    • Never store plain-text passwords: Use encodePassword():
      $user->setPassword($encoder->encodePassword($user, 'plainPassword'));
      
  3. Event Ordering:

    • Events like UserRegisteredEvent fire after the user is persisted. Use prePersist lifecycle callbacks for pre-save logic.
  4. API Overrides:

    • Customizing API resources requires replacing the entire resource class (not partial overrides):
      # config/packages/api_platform.yaml
      resources:
          App\Entity\CustomUser: ~
      

Debugging

  1. Doctrine Events: Enable SQL logging to debug queries:

    # config/packages/dev/doctrine.yaml
    dbal:
        logging: true
        profiling: true
    
  2. Event Debugging: Dump events in a listener:

    public function onUserRegistered(UserRegisteredEvent $event): void
    {
        dump($event->getUser()); // Debug user data
    }
    
  3. Common Errors:

    • "Class not found": Ensure user_class in sylius_user.yaml matches your entity.
    • Validation errors: Check User constraints (e.g., #[Assert\Email]).

Extension Points

  1. Custom User Providers: Implement UserProviderInterface for non-database users (e.g., OAuth):

    class CustomUserProvider implements UserProviderInterface
    {
        public function loadUserByIdentifier(string $identifier): UserInterface
        {
            // Load user from external source
        }
    }
    

    Register in services.yaml:

    services:
        App\Security\CustomUserProvider:
            tags: [sylius.user_provider]
    
  2. Dynamic Roles: Use a UserRoleSubscriber to assign roles dynamically:

    public function onKernelRequest(GetResponseEvent $event): void
    {
        $user = $this->getUser();
        if ($user && $user->isPremium()) {
            $user->addRole('ROLE_PREMIUM');
        }
    }
    
  3. Multi-Tenancy: Extend User with a tenantId field and override loadUserByIdentifier to scope queries:

    public function loadUserByIdentifier(string $identifier): ?UserInterface
    {
        return $this->userRepository->findOneBy([
            'email' => $identifier,
            'tenantId' => $this->tenantId,
        ]);
    }
    
  4. Testing Utilities: Create a UserFactory for tests:

    // tests/Factory/UserFactory.php
    class UserFactory extends Factory
    {
        protected function define(): array
        {
            return [
                'email' => Faker::unique()->safeEmail(),
                'plainPassword' => 'password',
            ];
        }
    }
    

    Use in tests:

    $user = UserFactory::createOne();
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware