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

Laravel Model Activity Log Laravel Package

foxen/laravel-model-activity-log

Automatically log Eloquent model activity in Laravel: create, update (with attribute diffs), delete, and restore (SoftDeletes). Supports per-model log names, ignoring or redacting attributes, tracks the authenticated user or falls back to “System”, and can prune old entries.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Event-Driven Logging: Leverages Laravel’s built-in model events (created, updated, deleted, restored) to log activity without manual intervention, aligning well with Laravel’s Eloquent ecosystem.
    • Minimal Overhead: Uses traits (LogsActivity) for model integration, reducing boilerplate and maintaining separation of concerns.
    • Configurable: Supports pruning old logs via TTL (Time-To-Live) policies, reducing storage bloat.
    • Soft Deletes Compatibility: Automatically logs restored events if the model uses SoftDeletes.
    • Audit Trail: Provides a structured way to track changes (e.g., old_values and new_values for updates), useful for compliance or debugging.
  • Cons:

    • Limited Query Flexibility: Logs are stored in a single activity_log table, which may not scale for complex queries (e.g., multi-model joins, aggregations).
    • No Native Filtering: The package does not expose a query builder for logs (e.g., filtering by user, model, or time range) out of the box.
    • No Real-Time Notifications: Logs are passive; no built-in webhooks or event triggers for external systems.
    • Performance Impact: Logging every updated event (with old_values/new_values) could introduce overhead for high-frequency models.

Integration Feasibility

  • Laravel 12+ Compatibility: Requires PHP 8.3+, which may necessitate a PHP upgrade if the current stack is older.
  • Database Schema: Introduces a new table (activity_log) with a fixed schema, requiring migration and potential index tuning (e.g., for causer_id, model_type, or action).
  • Authentication Dependency: Relies on Laravel’s auth system to attribute actions to users (via causer_id). Systems without auth may need customization.
  • Testing Overhead: Adds complexity to model tests (e.g., verifying logs for edge cases like mass updates or transactions).

Technical Risk

  • Schema Evolution: Future changes to the activity_log table (e.g., adding columns) may require backward-compatible migrations.
  • Concurrency Issues: High-write models (e.g., e-commerce inventory) could face contention in the activity_log table during peak loads.
  • Data Retention: Pruning policies must be carefully configured to balance compliance needs (e.g., GDPR) and storage costs.
  • Debugging Complexity: Logs may obscure the root cause of issues (e.g., a failed update could generate both a success and error log).
  • Vendor Lock-in: Minimal adoption (0 stars/dependents) suggests unproven long-term viability, though MIT license mitigates risk.

Key Questions

  1. Use Case Alignment:

    • Is this primarily for auditing, debugging, or compliance? If compliance, does it meet regulatory requirements (e.g., immutable logs)?
    • Are there specific queries needed (e.g., "show all changes to Model X by User Y in the last 30 days") that the package doesn’t support natively?
  2. Performance:

    • What is the write volume for the most active models? Could logging updated events with old_values/new_values impact performance?
    • Are there read-heavy use cases (e.g., admin dashboards) that require optimized queries on the activity_log table?
  3. Authentication:

    • How are actions attributed to users? Will causer_id always be populated (e.g., for API calls or background jobs)?
    • Is there a fallback for anonymous/system actions (e.g., cron jobs, migrations)?
  4. Data Retention:

    • What is the expected log lifespan? Are there legal requirements for retention periods?
    • How will pruning be scheduled (e.g., Laravel scheduler, cron) and monitored?
  5. Extensibility:

    • Are there plans to extend the log schema (e.g., adding metadata like IP addresses, user agents)?
    • Could this replace or supplement existing logging (e.g., Laravel’s logs table or third-party tools like Sentry)?
  6. Alternatives:

    • Has Laravel Audit (laravel-audit) or Spatie Audit Logs been considered? How does this package compare in terms of features and maturity?
    • Is a custom solution (e.g., database triggers, event listeners) more appropriate for niche requirements?

Integration Approach

Stack Fit

  • Laravel 12+: Native integration via service provider and traits; no major framework conflicts.
  • PHP 8.3+: Requires upgrade if using an older version (e.g., 8.1). Features like readonly properties or enums may be leveraged in future updates.
  • Database: Supports MySQL, PostgreSQL, SQLite, and SQL Server (via Eloquent). Schema is simple but may need indexing for large datasets.
  • Authentication: Relies on Laravel’s auth system (Auth::user()). Custom logic may be needed for non-standard auth flows (e.g., API tokens, service accounts).
  • Testing: Compatible with Laravel’s testing tools (e.g., assertDatabaseHas for log verification).

Migration Path

  1. Dependency Update:

    • Upgrade PHP to 8.3+ and Laravel to 12+ if not already compliant.
    • Update composer.json and run composer update.
  2. Configuration:

    • Publish the config: php artisan vendor:publish --provider="Foxen\LaravelModelActivityLog\Providers\ActivityLogServiceProvider" --tag="config".
    • Customize foxen_activitylog.php (e.g., TTL settings, excluded models/actions).
  3. Database Migration:

    • Run php artisan migrate to create the activity_log table.
    • Consider adding indexes for frequently queried columns:
      Schema::table('activity_log', function (Blueprint $table) {
          $table->index(['model_type', 'model_id']);
          $table->index(['causer_id']);
          $table->index(['action']);
          $table->index(['created_at']);
      });
      
  4. Model Integration:

    • Add the LogsActivity trait to target models:
      use Foxen\LaravelModelActivityLog\Traits\LogsActivity;
      
      class Post extends Model {
          use LogsActivity;
          // ...
      }
      
    • Exclude models/actions if needed via config:
      'excluded_models' => [
          'App\Models\UnimportantModel',
      ],
      'excluded_actions' => [
          'forceDelete',
      ],
      
  5. Pruning Setup:

    • Schedule the pruning command (e.g., daily via Laravel scheduler):
      // app/Console/Kernel.php
      protected function schedule(Schedule $schedule) {
          $schedule->command('foxen:activity-log:prune')->daily();
      }
      
  6. Testing:

    • Write tests for critical models to verify logs are created/updated/deleted as expected.
    • Test edge cases (e.g., mass updates, transactions, soft deletes).

Compatibility

  • Existing Logs: No migration path for existing audit logs; this is a new table.
  • Third-Party Packages: Potential conflicts if other packages also log model activity (e.g., double-logging). Mitigate by:
    • Using the config to exclude overlapping models/actions.
    • Merging logs post-hoc if needed.
  • Custom Model Logic: Ensure boot() methods or observers don’t interfere with the trait’s event listeners.

Sequencing

  1. Phase 1: Pilot Models

    • Start with low-traffic models (e.g., Post, UserProfile) to test performance and log accuracy.
    • Validate pruning and query performance.
  2. Phase 2: Core Models

    • Roll out to high-value models (e.g., Order, Payment) with monitoring for performance impact.
  3. Phase 3: Full Rollout

    • Enable for all remaining models, adjusting TTL and exclusions as needed.
  4. Phase 4: Optimization

    • Add indexes, optimize queries, or extend the schema based on usage patterns.

Operational Impact

Maintenance

  • Package Updates:
    • Monitor for updates to the package (though low activity suggests infrequent releases).
    • Test updates thoroughly, especially for schema changes.
  • Configuration Drift:
    • Centralize foxen_activitylog.php settings (e.g., TTL, exclusions) to avoid per-environment inconsistencies.
  • Pruning:
    • Monitor pruning job logs for failures (e.g., database locks, timeouts).
    • Consider logging pruning metrics (e.g., "Deleted 10,000 logs in 5 minutes").

Support

  • Debugging:
    • Logs may help diagnose issues (e.g., "Why was this record updated?") but could also complicate debugging if logs are noisy.
    • Provide support teams with
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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