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

cast1el/user-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require friendsofsymfony/user-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        FriendsOfSymfony\UserBundle\FOSUserBundle::class => ['all' => true],
    ];
    
  2. Database Configuration: Update config/packages/doctrine.yaml to include the User entity:

    orm:
        mappings:
            FOSUserBundle: ../../vendor/friendsofsymfony/user-bundle/Resources/config/doctrine
    
  3. First Use Case: Run migrations to create the user table:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  4. Routing: Enable FOSUserBundle routes in config/routes.yaml:

    fos_user:
        resource: "@FOSUserBundle/Resources/config/routing/all.xml"
        prefix: /user
    

Implementation Patterns

Core Workflows

User Registration

  1. Form Integration: Extend the default registration form:

    // src/Form/RegistrationFormType.php
    use FOS\UserBundle\Form\Type\RegistrationFormType as BaseRegistrationFormType;
    
    class RegistrationFormType extends BaseRegistrationFormType {
        public function buildForm(FormBuilderInterface $builder, array $options) {
            parent::buildForm($builder, $options);
            $builder->add('custom_field', TextType::class);
        }
    }
    
  2. Controller Override: Override the registration controller to customize logic:

    // src/Controller/RegistrationController.php
    use FOS\UserBundle\Controller\RegistrationController as BaseRegistrationController;
    
    class RegistrationController extends BaseRegistrationController {
        public function registerAction() {
            // Custom logic (e.g., validation, email templates)
            return parent::registerAction();
        }
    }
    

Password Reset

  1. Email Templates: Override default templates in templates/FOSUserBundle/Registration/reset.html.twig.

  2. Token Lifecycle: Use the fos_user.user_manager service to manage tokens:

    $userManager = $this->get('fos_user.user_manager');
    $user = $userManager->findUserBy(['email' => 'user@example.com']);
    $token = $userManager->createResetToken($user);
    

Authentication Integration

  1. Security Configuration: Configure security.yaml to use FOSUserBundle’s provider:

    security:
        providers:
            fos_userbundle:
                id: fos_user.user_provider.username_email
        firewalls:
            main:
                form_login:
                    provider: fos_userbundle
    
  2. Custom User Provider: Extend the default provider for custom logic:

    // src/Security/UserProvider.php
    use FOS\UserBundle\Model\UserManagerInterface;
    
    class CustomUserProvider implements UserProviderInterface {
        private $userManager;
    
        public function __construct(UserManagerInterface $userManager) {
            $this->userManager = $userManager;
        }
    
        public function loadUserByUsername($username) {
            return $this->userManager->findUserBy(['username' => $username]);
        }
    }
    

Integration Tips

  1. Event Listeners: Subscribe to FOSUserBundle events (e.g., fos_user.registered) for post-actions:

    // src/EventListener/UserListener.php
    use FOS\UserBundle\FOSUserEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class UserListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                FOSUserEvents::REGISTERED => 'onUserRegistered',
            ];
        }
    
        public function onUserRegistered(GetResponseUserEvent $event) {
            // Send welcome email, log activity, etc.
        }
    }
    
  2. Custom User Class: Extend the default User entity:

    // src/Entity/User.php
    use FOS\UserBundle\Model\User as BaseUser;
    
    class User extends BaseUser {
        /**
         * @ORM\Column(type="string", length=255, nullable=true)
         */
        private $customField;
    
        // Getters/setters
    }
    
  3. API Integration: Use FOSUserBundle with API Platform or Symfony Serializer:

    # config/packages/api_platform.yaml
    resources:
        App\Entity\User:
            collectionOperations:
                get:
                    security: "is_granted('ROLE_ADMIN')"
    

Gotchas and Tips

Pitfalls

  1. Route Conflicts: FOSUserBundle routes may conflict with existing routes. Use prefix in routing.yaml or override controllers to avoid clashes.

  2. Doctrine Migrations: Always run doctrine:migrations:diff after extending the User entity to update the schema.

  3. Security Context: FOSUserBundle does not handle authentication—pair it with Symfony’s SecurityBundle for full auth functionality.

  4. Token Expiry: Reset tokens expire by default (configurable in config/packages/fos_user.yaml). Ensure your reset route respects this:

    fos_user:
        reset:
            token_ttl: 86400  # 1 day in seconds
    

Debugging

  1. Event Debugging: Enable Symfony’s event dispatcher debug mode:

    php bin/console debug:event-dispatcher
    
  2. Form Errors: Validate custom fields in the registration form:

    $builder->add('custom_field', TextType::class, [
        'constraints' => [new NotBlank(), new Length(['max' => 100])],
    ]);
    
  3. User Loading: If users aren’t loading, verify your UserProvider and UserManager services are properly configured in services.yaml:

    services:
        App\Security\UserProvider:
            arguments:
                - '@fos_user.user_manager'
    

Extension Points

  1. Custom Validation: Add constraints to the User entity:

    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @Assert\Unique(entityManager="doctrine.orm.entity_manager", message="Email already taken")
     */
    private $email;
    
  2. Profile Management: Extend the profile controller to add fields:

    // src/Controller/ProfileController.php
    use FOS\UserBundle\Controller\ProfileController as BaseProfileController;
    
    class ProfileController extends BaseProfileController {
        public function editAction() {
            $form = $this->container->get('fos_user.user_manager')->createEditForm($this->getUser());
            $form->add('custom_field', TextType::class);
            // ...
        }
    }
    
  3. MongoDB/CouchDB: For ODM support, configure fos_user in config/packages/fos_user.yaml:

    fos_user:
        db_driver: orm  # or 'mongodb', 'couchdb'
    
  4. Translation: Override translations in translations/messages.en.yaml:

    'Registration completed': 'Welcome aboard! Your account is now active.'
    
  5. Testing: Use the FOS\UserBundle\Tests\Functional\WebTestCase base class for functional tests:

    use FOS\UserBundle\Tests\Functional\WebTestCase;
    
    class UserRegistrationTest extends WebTestCase {
        public function testRegistration() {
            $client = static::createClient();
            // ...
        }
    }
    
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver