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

Userstamps Laravel Package

wildside/userstamps

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require wildside/userstamps
    

    Ensure your Laravel version is 9+ and PHP is 8.2+.

  2. Database Migration: Add the columns to your model’s migration using the helper methods:

    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->userstamps(); // Adds `created_by`, `updated_by`
        $table->timestamps();
    });
    

    For UUIDs:

    $table->userstampsUuid();
    
  3. Apply the Trait: Add HasUserstamps to your Eloquent model:

    use Wildside\Userstamps\HasUserstamps;
    
    class Post extends Model
    {
        use HasUserstamps;
    }
    
  4. First Use Case: Create a record—created_by and updated_by will auto-populate with the authenticated user’s ID:

    $post = Post::create(['title' => 'Hello World']);
    // $post->created_by === auth()->id();
    

Implementation Patterns

Core Workflows

  1. Automatic User Tracking:

    • No manual assignment needed for created_by/updated_by on create()/update().
    • Example: Audit logs or activity feeds leverage these fields directly:
      $post->createdBy->name; // Access related user
      
  2. Soft Deletes Integration:

    • Add deleted_by via migration:
      $table->userstampSoftDeletes();
      
    • Track who deleted records:
      $post->delete(); // $post->deleted_by === auth()->id();
      
  3. Customizing User Resolution:

    • Override the user resolver in your model:
      class Post extends Model
      {
          use HasUserstamps;
      
          protected function getUserstampUser()
          {
              return User::findOrFail(123); // Force a specific user
          }
      }
      
  4. Query Scopes:

    • Filter by user actions:
      Post::createdBy(User::first())->get();
      Post::updatedBy(User::first())->get();
      
  5. API/Queue Jobs:

    • Ensure the authenticated user context is preserved (e.g., via middleware or auth() in jobs).

Integration Tips

  • Middleware: Use auth middleware to ensure created_by/updated_by are set only for logged-in users.
  • Testing: Mock the authenticated user:
    $this->actingAs($user)->post('/posts', ['title' => 'Test']);
    
  • Polymorphic Relations: Combine with morphTo for multi-model tracking:
    $table->morphs('userstampable');
    

Gotchas and Tips

Pitfalls

  1. Missing Authentication:

    • If no user is authenticated, created_by/updated_by will be null. Handle this in your logic or set a default user:
      protected function getUserstampUser()
      {
          return auth()->check() ? auth()->user() : User::DEFAULT_SYSTEM_USER;
      }
      
  2. Column Type Mismatch:

    • Ensure created_by/updated_by match your users.id column type (e.g., unsignedBigInteger for bigIncrements()).
  3. Soft Deletes Conflicts:

    • If using SoftDeletes, ensure deleted_at and deleted_by are both present. The package won’t add deleted_at—use SoftDeletes trait separately.
  4. UUIDs:

    • For UUIDs, use userstampsUuid() but ensure your users.id is a UUID column (e.g., Uuid type in Laravel).

Debugging

  • Check Resolver: Verify getUserstampUser() returns the expected user:
    dd($model->getUserstampUser());
    
  • Migration Errors: Run php artisan migrate:fresh if column types are incorrect.

Extension Points

  1. Custom Columns: Override getUserstampColumns() to use non-standard column names:

    protected function getUserstampColumns()
    {
        return ['author_id', 'editor_id'];
    }
    
  2. Event Hooks: Listen for userstamp.created/userstamp.updated events to trigger side effects:

    event(new PostCreated($post));
    
  3. Batch Operations: The package doesn’t auto-fill during insert() or update() queries. Use model instances or manual assignment for bulk operations:

    Post::insert([...]); // Won't auto-set userstamps
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle