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 Laravel Package

sylius/user

Sylius User component: user and customer models plus authentication-related interfaces and utilities for Sylius-based apps. Provides reusable building blocks for user management, security integration, and account features in Symfony/Laravel-adjacent PHP projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require sylius/user
    

    Publish migrations and configuration (if needed):

    php artisan vendor:publish --provider="Sylius\User\SyliusUserServiceProvider"
    

    Run migrations:

    php artisan migrate
    
  2. Basic Usage The package provides a User model (extendable) and a UserRepository for CRUD operations. Example:

    use Sylius\User\Model\UserInterface;
    use Sylius\User\Repository\UserRepositoryInterface;
    
    // Create a user
    $user = new \Sylius\User\Model\User();
    $user->setEmail('user@example.com');
    $user->setPlainPassword('secure123'); // Handles hashing automatically
    $userRepository->add($user);
    
    // Find a user
    $user = $userRepository->findOneBy(['email' => 'user@example.com']);
    
  3. First Use Case: Authentication Integrate with Laravel’s built-in auth:

    // config/auth.php
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => \Sylius\User\Model\User::class,
        ],
    ],
    

    Now use Auth::user() as usual.


Implementation Patterns

Core Workflows

  1. User Management

    • Creation: Use User model with setters (e.g., setEmail(), setPlainPassword()). Passwords are auto-hashed via UserPasswordUpdater.
    • Updates: Use UserPasswordUpdater for password changes:
      $updater = new \Sylius\User\Updater\UserPasswordUpdater();
      $updater->update($user, 'newPassword123');
      
    • Deletion: Soft-deletes via SoftDeletableTrait (if enabled).
  2. Repository Integration

    • Inject UserRepositoryInterface for queries:
      $user = $userRepository->findOneBy(['email' => 'test@example.com']);
      $users = $userRepository->findBy(['role' => 'ROLE_ADMIN']);
      
    • Extend UserRepository for custom logic:
      class CustomUserRepository extends UserRepository {}
      
  3. Events & Listeners

    • Dispatch events (e.g., UserCreated, UserUpdated) via UserEvents:
      event(new UserCreated($user));
      
    • Listen for events in service providers:
      $dispatcher->addListener(
          UserEvents::CREATED,
          function (UserCreatedEvent $event) { /* ... */ }
      );
      

Integration Tips

  • Roles/Permissions: Pair with spatie/laravel-permission for RBAC:
    $user->assignRole('admin');
    
  • APIs: Use Sylius\Component\User\Security\PasswordGenerator for secure password generation.
  • Testing: Mock UserRepositoryInterface for unit tests:
    $this->mock(UserRepositoryInterface::class)->shouldReceive('findOneBy')->andReturn($user);
    

Gotchas and Tips

Pitfalls

  1. Password Hashing

    • Issue: Forgetting setPlainPassword() and manually hashing passwords.
    • Fix: Always use setPlainPassword()—the package handles hashing via UserPasswordUpdater.
    • Debug: Check UserPasswordUpdater for errors if passwords fail to validate.
  2. Soft Deletes

    • Issue: find() returns null for soft-deleted users by default.
    • Fix: Use findOneBy() or enable withTrashed():
      $userRepository->findOneBy(['email' => 'test@example.com'], null, null, ['trashed' => true]);
      
  3. Event Dispatching

    • Issue: Events not firing due to missing EventDispatcher binding.
    • Fix: Ensure SyliusUserServiceProvider is registered and events are dispatched manually if needed:
      $dispatcher->dispatch(new UserCreated($user));
      

Debugging

  • Logs: Enable Sylius logs in config/logging.php for user-related events.
  • Database: Verify migrations for users table (check for deleted_at if soft deletes are enabled).
  • Tests: Use sylius/user-tests for test utilities (if available).

Extension Points

  1. Custom User Model Extend \Sylius\User\Model\User to add fields:

    class CustomUser extends User
    {
        protected $customField;
    
        public function setCustomField($value): void
        {
            $this->customField = $value;
        }
    }
    

    Update config/auth.php to point to CustomUser.

  2. Custom Repository Override UserRepository methods:

    class CustomUserRepository extends UserRepository
    {
        public function findByRole(string $role): array
        {
            return $this->createQueryBuilder('u')
                ->where('u.role = :role')
                ->setParameter('role', $role)
                ->getQuery()
                ->getResult();
        }
    }
    
  3. Password Rules Customize validation in UserPasswordUpdater:

    $validator = Validator::make(['password' => $plainPassword], [
        'password' => ['required', 'min:12', 'regex:/[A-Z]/'], // Custom rules
    ]);
    

Config Quirks

  • Default Roles: No built-in role system—use spatie/laravel-permission or similar.
  • Email Uniqueness: Enforced via UniqueEntity validator (check User model constraints).
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.
yandex/translate-api
voku/simple_html_dom
league/flysystem-vfs
bkwld/upchuck
filament/spatie-laravel-tags-plugin
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php