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

bengor-user/user

Lightweight, flexible user management library built with Domain-Driven Design. Includes registration (basic/confirmation/invitation), password changes and resets, login/logout, user removal, role grant/revoke, and purging outdated invitation/remember tokens.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bengor-user/user
    

    Add to config/app.php under providers:

    BenGor\User\UserServiceProvider::class,
    

    Publish the config:

    php artisan vendor:publish --provider="BenGor\User\UserServiceProvider"
    
  2. First Use Case: Basic Registration

    use BenGor\User\User;
    use BenGor\User\Services\UserService;
    
    $userService = app(UserService::class);
    $user = $userService->register([
        'email' => 'user@example.com',
        'password' => 'secure123',
        'name' => 'John Doe',
    ]);
    
  3. Where to Look First

    • Config File: config/bengor-user.php (customize token TTL, password rules, etc.)
    • Service Class: BenGor\User\Services\UserService (core methods for CRUD operations)
    • Domain Models: BenGor\User\User, BenGor\User\Role (entities and their invariants)
    • Events: BenGor\User\Events (listen for UserRegistered, PasswordChanged, etc.)

Implementation Patterns

Core Workflows

  1. Registration Variants

    • Basic Registration:
      $userService->register($userData);
      
    • Confirmation Flow:
      $token = $userService->generateConfirmationToken($user);
      // Send email with $token
      $userService->confirmUser($user, $token);
      
    • Invitation-Based:
      $invitation = $userService->createInvitation($inviter, $email);
      // Send email with $invitation->token
      $user = $userService->acceptInvitation($invitation, $password);
      
  2. Authentication

    • Login:
      $user = $userService->login($email, $password);
      // Store $user->rememberToken in session
      
    • Logout:
      $userService->logout($user);
      
  3. Password Management

    • Change Password (with old password):
      $userService->changePassword($user, $oldPassword, $newPassword);
      
    • Forgot Password Flow:
      $token = $userService->generateRememberPasswordToken($email);
      // Send email with $token
      $userService->resetPassword($token, $newPassword);
      
  4. Role Management

    • Grant/Revoke Roles:
      $userService->grantRole($user, 'admin');
      $userService->revokeRole($user, 'admin');
      
    • Check Roles:
      if ($userService->hasRole($user, 'admin')) { ... }
      
  5. Token Cleanup

    • Purge Expired Tokens:
      $userService->purgeExpiredTokens();
      

Integration Tips

  1. Laravel Integration

    • Middleware: Use BenGor\User\Http\Middleware\Authenticate for route protection.
    • Service Binding: Bind UserService to Laravel’s container in AppServiceProvider:
      $this->app->bind('BenGor\User\Services\UserService', function ($app) {
          return new UserService(
              $app->make('BenGor\User\Repositories\UserRepository'),
              $app->make('BenGor\User\Repositories\RoleRepository'),
              $app->make('BenGor\User\Repositories\TokenRepository')
          );
      });
      
    • Events: Listen to UserRegistered to trigger welcome emails:
      UserRegistered::class => [MailService::class, 'sendWelcomeEmail'],
      
  2. Customizing User Model

    • Extend the base User model:
      namespace App\Models;
      
      use BenGor\User\User as BaseUser;
      
      class User extends BaseUser
      {
          protected $table = 'custom_users';
          protected $primaryKey = 'user_id';
      }
      
    • Update the UserRepository binding in UserServiceProvider to point to your custom repository.
  3. Testing

    • Use BenGor\User\Tests\TestCase as a base for unit/feature tests.
    • Mock UserService for isolated testing:
      $mockService = Mockery::mock(UserService::class);
      $mockService->shouldReceive('register')->andReturn($user);
      
  4. API Usage

    • Pair with Laravel’s Passport or Sanctum for API authentication:
      $userService->login($email, $password);
      $token = $user->createToken('API Token')->accessToken;
      

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • Tokens (confirmation, invitation, password reset) expire by default after 24 hours (configurable in bengor-user.php).
    • Fix: Call purgeExpiredTokens() periodically (e.g., via a scheduled task) to avoid token bloat.
  2. Password Rules

    • The package enforces minimum password length of 8 characters by default.
    • Override: Customize in bengor-user.php:
      'password' => [
          'min_length' => 10,
          'require_uppercase' => true,
      ],
      
  3. Email Uniqueness

    • The package assumes email uniqueness is handled at the database level (e.g., unique:users,email).
    • Gotcha: If you skip this, duplicate emails will cause silent failures during registration.
    • Fix: Add a unique constraint to your users table.
  4. Role Hierarchy

    • The package does not support role hierarchies (e.g., admin inheriting editor permissions).
    • Workaround: Manually check for hierarchical roles in your logic or extend the Role model.
  5. Session Management

    • The package does not handle session storage. You must manually:
      • Store user_id or remember_token in the session after login.
      • Clear the session on logout.
  6. Database Migrations

    • The package does not include migrations. You must create them manually or use Laravel’s make:migration:
      php artisan make:migration create_users_table
      
    • Required fields: id, email, password, remember_token, confirmed_at, created_at, updated_at.

Debugging Tips

  1. Token Issues

    • Check if tokens are being generated correctly:
      $token = $userService->generateConfirmationToken($user);
      // Verify token exists in database via `tokens` table.
      
    • Debug token expiry:
      $token = Token::where('token', $request->token)->first();
      if ($token->expires_at < now()) {
          throw new \Exception('Token expired');
      }
      
  2. Password Hashing

    • Ensure APP_KEY is set in .env (required for password hashing).
    • Verify hashing algorithm in bengor-user.php:
      'hash_algorithm' => 'bcrypt', // or 'argon2id'
      
  3. Role Assignment

    • Debug role assignments with:
      $user->roles; // Collection of assigned roles
      $userService->getRoles($user); // Alternative method
      
  4. Event Listeners

    • If events aren’t firing, check:
      • The event is registered in EventServiceProvider.
      • The listener method signature matches (e.g., handle(UserRegistered $event)).

Extension Points

  1. Custom Validation

    • Extend the User model to add custom validation rules:
      public function rules()
      {
          return array_merge(parent::rules(), [
              'custom_field' => 'required|unique:users',
          ]);
      }
      
  2. Custom Repositories

    • Implement your own repository interfaces (UserRepository, RoleRepository) to override default behavior:
      class CustomUserRepository implements UserRepository
      {
          public function findByEmail($email)
          {
              return User::where('email', $email)->where('active', 1)->first();
          }
      }
      
    • Bind it in UserServiceProvider:
      $this->app->bind('BenGor\User\Repositories\UserRepository', function ($app) {
          return new CustomUserRepository();
      });
      
  3. Custom Tokens

    • Extend the Token model to add custom token types:
      class CustomToken extends Token
      {
          protected $type = 'custom';
      }
      
    • Update TokenRepository to handle the new type.
  4. Custom Events

    • Dispatch custom events alongside built
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope