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

hanifhefaz/user-model-activity

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require hanifhefaz/user-model-activity
    php artisan vendor:publish --provider="Hanifhefaz\UserModelActivity\UserModelActivityServiceProvider"
    
    • Publishes the config file (config/usermodelactivity.php) and migration for the user_model_activities table.
  2. Run Migration

    php artisan migrate
    
    • Creates the user_model_activities table to store activity logs.
  3. Enable Activity Tracking Add the HasActivity trait to your Eloquent model:

    use Hanifhefaz\UserModelActivity\Traits\HasActivity;
    
    class User extends Model
    {
        use HasActivity;
    }
    
  4. First Use Case

    • Create/update/delete a model instance. The package automatically logs:
      • created (with created_at, user_id, and payload).
      • updated (with updated_at, user_id, changeset diff, and old/new values).
      • deleted (with deleted_at, user_id, and payload).

    Example:

    $user = new User(['name' => 'John Doe']);
    $user->save(); // Logs creation
    $user->name = 'Jane Doe';
    $user->save(); // Logs update
    

Implementation Patterns

Core Workflows

  1. Model-Level Tracking

    • Apply HasActivity trait to any Eloquent model to enable automatic logging.
    • Customize logged fields via the activityFields() method:
      class Post extends Model
      {
          use HasActivity;
      
          public function activityFields()
          {
              return ['title', 'content', 'published_at'];
          }
      }
      
  2. User Association

    • Logs include the user_id of the authenticated user performing the action.
    • Override the default user resolver in config/usermodelactivity.php:
      'user_resolver' => function () {
          return auth()->user() ?? null;
      },
      
  3. Querying Logs

    • Use the UserModelActivity model to fetch logs:
      $logs = UserModelActivity::whereModelType('App\Models\User')
          ->whereModelId(1)
          ->orderBy('created_at', 'desc')
          ->get();
      
  4. Event-Based Extensions

    • Listen to activity.created, activity.updated, or activity.deleted events:
      event(new CreatingUserModelActivity($user, $activity));
      
  5. Bulk Operations

    • For bulk inserts/updates, use Activity::logBulk() (if supported):
      User::where('active', false)->update(['active' => true]);
      // Logs each update individually (if configured).
      

Integration Tips

  • Middleware for Admin Context Attach middleware to admin routes to ensure logs include the correct user_id:

    Route::middleware(['auth', 'admin'])->group(function () {
        // Admin-only routes
    });
    
  • Soft Deletes Enable soft deletes on the UserModelActivity table to preserve logs even if models are restored:

    class UserModelActivity extends Model
    {
        use SoftDeletes;
    }
    
  • Storage Customization Override the default storage (e.g., database) by binding a custom logger in the service provider:

    $this->app->singleton('usermodelactivity.logger', function () {
        return new CustomLogger();
    });
    
  • API Logging Combine with Laravel’s log facade to cross-reference API activity:

    Log::info('User updated', ['user_id' => auth()->id(), 'changes' => $changes]);
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Logging every model change can impact performance for high-traffic applications.
    • Mitigation: Disable logging for non-critical models or use a queue:
      'queue_logging' => env('QUEUE_LOGGING', false),
      
  2. Missing User Context

    • Logs without a user_id (e.g., CLI commands or automated tasks) may lack accountability.
    • Fix: Set a default user in the resolver or manually attach a user:
      UserModelActivity::setUser($user);
      
  3. Diff Algorithm Limitations

    • The default diff for updates may not handle complex objects (e.g., JSON arrays) accurately.
    • Workaround: Use activityFields() to specify simple fields or extend the diff logic.
  4. Migration Conflicts

    • Publishing the migration may conflict with existing user_model_activities tables.
    • Solution: Review the migration before running or use --force cautiously.
  5. Event Ordering

    • Custom events fired alongside activity.* events may execute in unexpected orders.
    • Tip: Use event(new CustomEvent($activity))->afterCommitting() for consistency.

Debugging

  • Log Location Check the storage/logs/laravel.log for errors during logging (e.g., missing columns).

    • Ensure the user_model_activities table matches the migration schema.
  • Activity Payload Inspect the raw payload with:

    dd(UserModelActivity::latest()->first()->payload);
    
  • Disabled Logging Verify the trait is applied and logging isn’t disabled in config:

    'enabled' => env('USER_MODEL_ACTIVITY_ENABLED', true),
    

Extension Points

  1. Custom Loggers Extend the logger to support additional storage (e.g., Elasticsearch):

    class ElasticsearchLogger implements LoggerInterface
    {
        public function log($model, $event, $payload)
        {
            // Custom logic
        }
    }
    
  2. Activity Filters Add scopes to the UserModelActivity model for common queries:

    class UserModelActivity extends Model
    {
        public function scopeByModel($query, $model)
        {
            return $query->where('model_type', get_class($model));
        }
    }
    
  3. Webhook Notifications Trigger webhooks on critical activities:

    UserModelActivity::created(function ($activity) {
        if ($activity->event === 'deleted') {
            Http::post(config('services.slack.webhook'), [
                'text' => "Model {$activity->model_type} deleted by {$activity->user_id}"
            ]);
        }
    });
    
  4. Activity Retention Implement a cron job to purge old logs:

    // app/Console/Commands/CleanupLogs.php
    public function handle()
    {
        UserModelActivity::where('created_at', '<', now()->subMonths(6))->delete();
    }
    
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