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

amashukov/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 integrate FOSUserBundle’s provider:

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email
    

    Configure fos_user in config/packages/fos_user.yaml:

    fos_user:
        db_driver: orm       # or 'mongodb', 'couchdb'
        firewall_name: main
        user_class: App\Entity\User
    
  4. Create User Entity: Extend FOS\UserBundle\Model\User:

    // src/Entity/User.php
    namespace App\Entity;
    
    use FOS\UserBundle\Model\User as BaseUser;
    
    class User extends BaseUser {}
    
  5. Run Migrations:

    php bin/console doctrine:schema:update --force
    
  6. First Use Case: Register a user via the built-in controller (or create a custom form):

    php bin/console fos:user:create
    

Implementation Patterns

Core Workflows

  1. User Registration:

    • Use the default registration form or extend FOS\UserBundle\Form\Type\RegistrationFormType.
    • Override the registration template (registration.html.twig) or use the controller (FOS\UserBundle\Controller\RegistrationController).
    • Example custom form:
      // 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:

    • Trigger via fos:user:resetting:send-email command or the /resetting/request route.
    • Customize the reset token TTL in fos_user.yaml:
      resetting:
          token_ttl: 86400  # 1 day
      
  3. Authentication Integration:

    • Use fos_user.user_provider.username_email in security.yaml:
      firewalls:
          main:
              form_login:
                  provider: fos_userbundle
      
  4. Profile Management:

    • Extend the profile form (FOS\UserBundle\Form\Type\ProfileFormType) or override the controller.
    • Example: Add a profile picture field:
      $builder->add('avatar', FileType::class, ['label' => 'Profile Picture']);
      
  5. Event Listeners:

    • Listen to user lifecycle events (e.g., fos_user.registered):
      // 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(FilterUserResponseEvent $event) {
              // Send welcome email, etc.
          }
      }
      

Integration Tips

  1. Laravel-Specific Adaptations:

    • Use spatie/laravel-fosuserbundle (a Laravel wrapper) for seamless integration with Laravel’s ecosystem:
      composer require spatie/laravel-fosuserbundle
      
    • Configure in config/fos_user.php (Laravel’s style):
      'db_driver' => 'eloquent',
      'user_model' => App\Models\User::class,
      
  2. Custom User Model:

    • Extend Laravel’s Authenticatable alongside FOS\UserBundle\Model\User:
      use Illuminate\Foundation\Auth\User as Authenticatable;
      use FOS\UserBundle\Model\User as BaseUser;
      
      class User extends Authenticatable implements BaseUser {
          use FOS\UserBundle\Model\UserTrait;
      }
      
  3. Blade Templates:

    • Replace Twig templates with Blade by overriding the controller and rendering Blade views:
      return view('auth.register', ['form' => $form->createView()]);
      
  4. Route Customization:

    • Override routes in routes/web.php:
      Route::get('/register', 'FOS\UserBundle\Controller\RegistrationController@register')->name('fos_user_registration_register');
      
  5. Validation Rules:

    • Add Laravel validation rules to the FOSUser form:
      $builder->add('email', EmailType::class, [
          'constraints' => [
              new NotBlank(),
              new Email(),
              new Callback([$this, 'checkEmailUnique']),
          ],
      ]);
      

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony Components:

    • The package targets Symfony 2.8–5.0. Ensure your Laravel version aligns with compatible Symfony components (e.g., avoid Symfony 6+ if using older FOSUserBundle versions).
  2. Doctrine vs. Eloquent:

    • FOSUserBundle defaults to Doctrine ORM. For Laravel/Eloquent, use spatie/laravel-fosuserbundle or manually adapt the User entity to work with Eloquent’s query builder.
  3. Token Generation:

    • Password reset tokens are generated via FOS\UserBundle\Util\TokenGenerator. Override this class if you need custom token logic (e.g., UUIDs instead of hashes).
  4. Form Type Conflicts:

    • Avoid naming conflicts with Laravel’s built-in form types (e.g., password field). Use unique names:
      $builder->add('plainPassword', RepeatedType::class, [
          'type' => PasswordType::class,
          'first_name' => 'password',
          'second_name' => 'confirm_password',
      ]);
      
  5. Email Configuration:

    • FOSUserBundle relies on Symfony’s Swiftmailer. In Laravel, configure swiftmailer in .env or config/mail.php:
      MAIL_DRIVER=smtp
      MAIL_HOST=mail.example.com
      
  6. CSRF Protection:

    • Ensure CSRF tokens are enabled in forms. FOSUserBundle handles this by default, but custom forms may require manual token inclusion:
      {{ form_start(form, {'attr': {'novalidate': 'novalidate'}}) }}
          {{ form_row(form._token) }}  {# CSRF token #}
      

Debugging Tips

  1. Event Debugging:

    • Dump events in listeners to verify triggers:
      public function onUserRegistered(FilterUserResponseEvent $event) {
          dump($event->getUser());
          dump($event->getResponse());
      }
      
  2. Database Migrations:

    • If migrations fail, check the User entity’s table name (@ORM\Table(name="fos_user")). Override in Laravel:
      class User extends Authenticatable {
          protected $table = 'users';
      }
      
  3. Form Errors:

    • Validate form submission manually:
      $form->handleRequest($request);
      if (!$form->isValid()) {
          dd($form->getErrors(true)); // Debug errors
      }
      
  4. Token Expiry:

    • Test token expiry by manually setting a short TTL in fos_user.yaml:
      resetting:
          token_ttl: 10  # 10 seconds for testing
      

Extension Points

  1. Custom User Fields:

    • Add fields to the User entity and update the form type:
      // src/Entity/User.php
      /**
       * @ORM\Column(type="string", length=255, nullable=true)
       */
      private $phoneNumber;
      
  2. Role Management:

    • Extend the role system by overriding getRoles() or adding a Role entity:
      public function getRoles() {
          $roles = $this->roles;
          $roles[] = 'ROLE_CUSTOM';
          return array_unique($roles);
      }
      
  3. Profile Picture Handling:

    • Use VichUploaderBundle for file uploads:
      composer require vich/uploader-bundle
      
      Configure in fos_user.yaml:
      service:
          user_class: App\Entity\User
          user_manager: fos_user.user_manager.default
      
  4. API Integration:

    • Create API endpoints for user actions (
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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