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

moox/user

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require moox/user
    php artisan mooxuser:install
    
    • This runs migrations, publishes config, and sets up default roles/permissions (if any).
  2. First Use Case:

    • User Creation:
      use Moox\User\Models\User;
      
      $user = User::create([
          'name' => 'John Doe',
          'email' => 'john@example.com',
          'password' => bcrypt('secure123'),
      ]);
      
    • Authentication:
      use Illuminate\Support\Facades\Auth;
      
      if (Auth::attempt(['email' => 'john@example.com', 'password' => 'secure123'])) {
          // Authenticated
      }
      
  3. Where to Look First:

    • Config: config/mooxuser.php (published via vendor:publish).
    • Models: app/Models/User.php (extended from Moox\User\Models\User).
    • Migrations: database/migrations/[timestamp]_create_users_table.php.

Implementation Patterns

Core Workflows

  1. User Management:

    • CRUD Operations:
      // Create
      $user = User::create([...]);
      
      // Read
      $user = User::find(1);
      
      // Update
      $user->update(['name' => 'Updated Name']);
      
      // Delete (soft delete if enabled)
      $user->delete();
      
    • Query Scopes:
      use Moox\User\Models\User;
      
      $activeUsers = User::active()->get(); // Assuming 'active' scope exists
      
  2. Authentication & Authorization:

    • Guard Integration:
      // Authenticate via API
      $credentials = $request->only('email', 'password');
      if (Auth::guard('api')->attempt($credentials)) {
          $token = $request->user()->createToken('API Token')->plainTextToken;
      }
      
    • Gate/Policy Usage:
      // Define a policy
      php artisan make:policy PostPolicy --model=Post
      
      // Use in controller
      $this->authorize('update', $post);
      
  3. Roles/Permissions (if supported):

    • Assign Roles:
      $user->assignRole('admin'); // Hypothetical; check package docs
      
    • Check Permissions:
      if ($user->can('edit-posts')) {
          // Granted
      }
      
  4. Events & Listeners:

    • Listen for User Events:
      // In EventServiceProvider
      protected $listen = [
          'Moox\User\Events\UserRegistered' => [
              'App\Listeners\SendWelcomeEmail',
          ],
      ];
      
  5. API Resources:

    • Transform User Data:
      php artisan make:resource UserResource --model=User
      
      return new UserResource($user);
      

Integration Tips

  • Extend User Model:
    namespace App\Models;
    
    use Moox\User\Models\User as MooxUser;
    
    class User extends MooxUser {
        protected $casts = [
            'is_admin' => 'boolean',
        ];
    }
    
  • Custom Validation:
    use Illuminate\Validation\Rule;
    
    $validated = $request->validate([
        'email' => ['required', Rule::unique('users')->ignore($user->id)],
    ]);
    
  • Seeding Users:
    // database/seeds/UsersTableSeeder.php
    use Moox\User\Models\User;
    use Illuminate\Database\Seeder;
    
    class UsersTableSeeder extends Seeder {
        public function run() {
            User::create([
                'name' => 'Admin',
                'email' => 'admin@example.com',
                'password' => bcrypt('admin123'),
            ]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • If you manually modify the users table after installation, run php artisan mooxuser:install --force to re-publish migrations (if supported).
    • Tip: Always back up your database before running migrations.
  2. Config Overrides:

    • Custom config values in config/mooxuser.php may be overwritten during package updates. Use config_array_merge_recursive in your AppServiceProvider to preserve settings:
      public function boot() {
          config(['mooxuser.custom_setting' => env('MOOXUSER_CUSTOM_SETTING', 'default')]);
      }
      
  3. Authentication Guard Assumptions:

    • The package may assume a default guard (e.g., web). Explicitly specify guards in Auth::guard('name') to avoid ambiguity.
  4. Soft Deletes:

    • If soft deletes are enabled ('softDeletes' => true in config), use:
      $user = User::withTrashed()->find(1); // Find even if soft-deleted
      $user->forceDelete(); // Permanently delete
      
  5. Event Binding:

    • If events (e.g., UserRegistered) aren’t firing, verify:
      • The event is properly subscribed in EventServiceProvider.
      • The listener class exists and is autoloaded.

Debugging

  • Log User Actions:
    use Moox\User\Models\User;
    use Illuminate\Support\Facades\Log;
    
    User::created(function ($user) {
        Log::info('New user created', ['user_id' => $user->id]);
    });
    
  • Check for Middleware:
    • Ensure auth middleware is applied to routes requiring authentication:
      Route::middleware(['auth:sanctum'])->get('/user', function () {
          return response()->json(['user' => auth()->user()]);
      });
      

Extension Points

  1. Custom Fields:

    • Add fields to the users table via migration, then extend the model:
      class User extends MooxUser {
          protected $fillable = ['name', 'email', 'password', 'custom_field'];
      }
      
  2. Custom Auth Logic:

    • Override the AuthenticatesUsers trait in a custom controller:
      use Moox\User\Traits\Auth\AuthenticatesUsers;
      
      class CustomLoginController extends Controller {
          use AuthenticatesUsers;
      
          protected function credentials(Request $request) {
              return $request->only('email', 'password', 'custom_auth_field');
          }
      }
      
  3. API Token Customization:

    • Extend the HasApiTokens trait or override token generation:
      use Laravel\Sanctum\HasApiTokens;
      
      class User extends MooxUser {
          use HasApiTokens;
      
          public function createToken($name = null) {
              return $this->tokens()->create([
                  'name' => $name ?? 'Personal Access Token',
                  'abilities' => ['*'], // Customize permissions
              ]);
          }
      }
      
  4. Observers:

    • Attach observers to the User model for pre/post actions:
      // app/Observers/UserObserver.php
      class UserObserver {
          public function creating(User $user) {
              $user->uuid = Str::uuid()->toString();
          }
      }
      
      // Register in AppServiceProvider
      User::observe(UserObserver::class);
      
  5. Testing:

    • Use factories for consistent test data:
      // database/factories/UserFactory.php
      $factory->define(User::class, function (Faker $faker) {
          return [
              'name' => $faker->name,
              'email' => $faker->unique()->safeEmail,
              'password' => bcrypt('password'),
          ];
      });
      
    • Test authentication:
      $user = User::factory()->create();
      $this->actingAs($user);
      $this->assertAuthenticated();
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity