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

atheon/user-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require friendsofsymfony/user-bundle
    

    Ensure Symfony\Bundle\FrameworkBundle\FrameworkBundle and Symfony\Bundle\SecurityBundle\SecurityBundle are installed.

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        FriendsOfSymfony\UserBundle\FOSUserBundle::class => ['all' => true],
    ];
    
  3. Configure Database & Security: Update config/packages/security.yaml to include:

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email
    firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
            logout: true
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
    
  4. First Use Case: Generate a user registration form and controller:

    php bin/console fos:user:create-form
    php bin/console fos:user:create-controller
    

Implementation Patterns

Core Workflows

  1. User Registration:

    • Extend FOS\UserBundle\Model\User to add custom fields (e.g., Profile entity).
    • Use the built-in registration form (FOS\UserBundle\Form\Type\RegistrationFormType) or override it:
      // src/Form/RegistrationFormType.php
      use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
      
      class RegistrationFormType extends BaseType {
          public function buildForm(FormBuilderInterface $builder, array $options) {
              parent::buildForm($builder, $options);
              $builder->add('custom_field', TextType::class);
          }
      }
      
  2. Password Reset:

    • Leverage the FOS\UserBundle\Event\GetResponseUserEvent to customize reset emails.
    • Override the reset template (templates/FOSUserBundle/Registration/reset.html.twig).
  3. Authentication:

    • Use the fos_user.user_provider in security.yaml for user loading.
    • Customize login/logout paths in security.yaml:
      form_login:
          login_path: /login
          check_path: /login_check
          default_target_path: /dashboard
      
  4. Profile Management:

    • Extend the ProfileController to add custom actions (e.g., avatar upload):
      // src/Controller/ProfileController.php
      use FOS\UserBundle\Controller\ProfileController as BaseController;
      
      class ProfileController extends BaseController {
          public function uploadAvatarAction() {
              // Custom logic
          }
      }
      

Integration Tips

  • Doctrine ORM: Ensure your User entity extends FOS\UserBundle\Model\User and uses ORM\Mapping as ORM:
    use FOS\UserBundle\Model\User as BaseUser;
    
    class User extends BaseUser {
        /**
         * @ORM\Column(type="string", length=255, nullable=true)
         */
        private $customField;
    }
    
  • Twig Extensions: Use fos_user helpers in templates:
    {{ fos_user.has_role('ROLE_ADMIN') ? 'Admin' : 'User' }}
    
  • Event Listeners: Subscribe to events like FOS\UserBundle\Event\FormEvent to modify form behavior:
    // src/EventListener/UserListener.php
    use FOS\UserBundle\Event\FormEvent;
    use FOS\UserBundle\Event\FormEventInterface;
    
    class UserListener {
        public function onUserForm(FormEvent $event) {
            $form = $event->getForm();
            $form->add('custom_field');
        }
    }
    
    Register in services.yaml:
    services:
        App\EventListener\UserListener:
            tags:
                - { name: kernel.event_listener, event: fos_user.registration.form.initialized, method: onUserForm }
    

Gotchas and Tips

Common Pitfalls

  1. Missing Configuration:

    • Forgetting to configure fos_user in config/packages/security.yaml or config/packages/fos_user.yaml will break authentication.
    • Fix: Run php bin/console fos:user:setup to generate default configs.
  2. Entity Inheritance Issues:

    • If your User entity doesn’t extend BaseUser or lacks required annotations (e.g., @ORM\Entity), migrations fail.
    • Fix: Verify your User entity matches the official example.
  3. CSRF Token Mismatches:

    • Custom login forms may fail if the CSRF token isn’t included or the csrf_token_generator isn’t configured.
    • Fix: Ensure your login form includes:
      {{ form_start(form, {'attr': {'novalidate': 'novalidate'}}) }}
      {{ form_row(form._token) }}
      
  4. Email Confirmation Delays:

    • Emails may not send if swiftmailer or mailer isn’t configured.
    • Fix: Verify MAILER_DSN in .env or config/packages/mailer.yaml.
  5. Route Conflicts:

    • FOSUserBundle’s routes (e.g., /register, /resetting) may conflict with custom routes.
    • Fix: Override routes in config/routes.yaml:
      fos_user:
          resource: "@FOSUserBundle/Resources/config/routing/all.xml"
          prefix: /auth
      

Debugging Tips

  • Enable Debug Mode:

    php bin/console debug:config fos_user
    

    Check for misconfigurations in security.yaml or fos_user.yaml.

  • Log Events: Subscribe to FOS\UserBundle\Event\FilterUserResponseEvent to log user actions:

    public function onUserResponse(FilterUserResponseEvent $event) {
        \Log::info('User action:', ['user' => $event->getUser(), 'response' => $event->getResponse()]);
    }
    
  • Test with fos:user:fixtures: Load test users via:

    php bin/console fos:user:create --super-admin
    

Extension Points

  1. Custom User Classes:

    • Override FOS\UserBundle\Model\UserInterface for custom logic (e.g., soft deletes):
      class CustomUser extends BaseUser implements UserInterface {
          public function isActive() {
              return $this->deletedAt === null;
          }
      }
      
  2. Dynamic Forms:

    • Use FormEvent to add/remove fields dynamically:
      public function onRegistrationForm(FormEvent $event) {
          $form = $event->getForm();
          if ($event->getRequest()->get('is_admin')) {
              $form->add('admin_field');
          }
      }
      
  3. API Integration:

    • Disable CSRF for API endpoints by creating a custom firewall:
      firewalls:
          api:
              pattern: ^/api
              stateless: true
              anonymous: true
              form_login:
                  provider: fos_userbundle
                  check_path: /api/login_check
                  username_parameter: _username
                  password_parameter: _password
      
  4. Multi-Tenant Support:

    • Extend the UserManager to scope users by tenant:
      class TenantUserManager extends UserManager {
          public function findUserBy(array $criteria) {
              $criteria['tenantId'] = $this->tenantId;
              return parent::findUserBy($criteria);
          }
      }
      
    • Register as a service:
      services:
          fos_user.user_manager.tenant:
              class: App\Service\TenantUserManager
              parent: fos_user.user_manager.default
              arguments: ['@fos_user.user_manager.default.orm', '@tenant.context']
      
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