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 Activitylog Laravel Package

spatie/laravel-activitylog

Log user and model activity in Laravel with a simple API. Automatically record Eloquent model events, link actions to subjects and causers, store custom properties, and query a dedicated activity_log table for auditing and history.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven Observability: The package excels as a lightweight, event-driven observability layer for Laravel applications, aligning with modern microservices and audit trail requirements. It integrates seamlessly with Eloquent models and manual logging, making it ideal for tracking user actions, system events, or model changes.
  • Separation of Concerns: The package enforces a clean separation between business logic and audit logging, reducing clutter in controllers or services. This is particularly valuable in large-scale applications where audit trails are critical for compliance (e.g., GDPR, SOX).
  • Extensibility: The beforeLogging hook and custom LogOptions allow for deep customization, such as enriching logs with metadata (e.g., IP addresses, request IDs) or filtering sensitive attributes. This makes it adaptable to niche use cases like batch processing or multi-tenant systems.
  • Database Agnostic: While it relies on Laravel’s Eloquent, the package abstracts the storage layer, making it compatible with any database supported by Laravel (MySQL, PostgreSQL, SQLite, etc.). The activity_log table schema is simple and can be extended without breaking changes.

Integration Feasibility

  • Low Friction: Installation and setup are minimal (composer + migration), with sensible defaults that require no configuration for basic use. The package auto-registers, reducing boilerplate.
  • Model-Level Integration: The LogsActivity trait enables automatic logging for Eloquent models with minimal code changes (e.g., use LogsActivity). This is a significant advantage for applications with hundreds of models, as it eliminates manual event listeners.
  • Facade-Based API: The Activity facade provides a fluent interface for manual logging, which is intuitive and reduces cognitive load for developers. Example:
    activity()->performedOn($order)->causedBy($user)->log('Order updated');
    
  • Compatibility: Works out-of-the-box with Laravel 8+ (tested up to Laravel 11). The package’s maturity (5K+ stars, active maintenance) and MIT license reduce adoption risk.

Technical Risk

  • Performance Overhead: Logging every model change or user action can impact performance, especially for high-throughput systems. Mitigation strategies include:
    • Selective Logging: Use logOnlyDirty() or dontLogIfAttributesChangedOnly() to minimize writes.
    • Async Processing: Offload logging to a queue (e.g., Laravel Queues) to decouple audit trails from request processing.
    • Batch Writes: Leverage the beforeLogging hook to batch related activities (e.g., using batch_uuid).
  • Storage Bloat: The activity_log table can grow rapidly in high-activity systems. Solutions include:
    • Archival: Implement a retention policy (e.g., purge old logs via Laravel Scheduler).
    • Partitioning: Use database partitioning or sharding for large-scale deployments.
    • Read Replicas: Offload read-heavy queries (e.g., Activity::all()) to replicas.
  • Schema Customization: The default migration assumes integer IDs. Applications using UUIDs or custom ID types must manually adjust the migration, which could be overlooked in CI/CD pipelines.
  • Dependency on Laravel: The package is tightly coupled to Laravel’s ecosystem (Eloquent, Facades, Service Providers). Porting to non-Laravel PHP applications would require significant refactoring.

Key Questions

  1. Audit Requirements:
    • What are the compliance or business requirements for audit trails (e.g., retention period, immutability, access controls)?
    • Are there legal constraints on what can be logged (e.g., PII, sensitive fields)?
  2. Performance Trade-offs:
    • What is the acceptable latency impact of logging? Can async processing be implemented?
    • How will the team monitor activity_log table growth and performance?
  3. Customization Needs:
    • Are there specific metadata fields (e.g., request IDs, geolocation) that must be included in every log?
    • Will multiple "logs" (e.g., default, admin_actions, api_events) be needed, or is a single table sufficient?
  4. Scaling Strategy:
    • How will the team handle read-heavy queries (e.g., dashboards, exports) as the activity_log table grows?
    • Are there plans to replicate or shard the audit data for scalability?
  5. Tooling Integration:
    • Will logs be consumed by external tools (e.g., ELK, Datadog, custom dashboards)? If so, how will the schema be adapted?
    • Are there plans to expose logs via an API or GraphQL for frontend consumption?

Integration Approach

Stack Fit

  • Laravel Ecosystem: The package is a perfect fit for Laravel applications, especially those using Eloquent for data modeling. It integrates natively with:
    • Eloquent Models: Automatic logging via traits (LogsActivity).
    • Service Containers: Dependency injection for CauserResolver and hooks.
    • Artisan Commands: Migration publishing and configuration.
  • PHP Extensions: No PHP extensions are required, making it compatible with any Laravel-compatible hosting (shared, VPS, serverless).
  • Database Compatibility: Works with any database supported by Laravel, though schema adjustments may be needed for non-integer IDs.
  • Queue Systems: Can be paired with Laravel Queues to offload logging (e.g., using beforeLogging to batch activities).

Migration Path

  1. Assessment Phase:
    • Audit existing logging mechanisms (e.g., custom tables, third-party tools) to identify gaps or redundancies.
    • Define scope: Which models/users/actions require logging? Prioritize high-value entities (e.g., User, Order, Payment).
  2. Pilot Integration:
    • Start with a single model (e.g., User) to test the LogsActivity trait and manual logging.
    • Validate the activity_log schema and adjust for custom ID types (e.g., UUIDs).
    • Implement a beforeLogging hook to add metadata (e.g., request_id, user_agent).
  3. Incremental Rollout:
    • Gradually add LogsActivity to additional models, starting with those with high change frequency.
    • For complex models, customize getActivitylogOptions() to optimize logging (e.g., logOnlyDirty).
    • Replace custom event listeners with the package where possible to reduce maintenance overhead.
  4. Advanced Features:
    • Implement multi-log support (e.g., admin_log, api_log) if different audit requirements exist.
    • Add retention policies (e.g., Laravel Scheduler job to purge logs older than 6 months).
    • Integrate with external systems (e.g., webhooks to forward critical events).

Compatibility

  • Laravel Versions: Tested with Laravel 8–11. For older versions, check the upgrade guide for breaking changes.
  • PHP Versions: Requires PHP 8.0+. Ensure your environment meets this requirement.
  • Database Drivers: Compatible with MySQL, PostgreSQL, SQLite, and SQL Server. For non-relational databases, consider a custom storage adapter.
  • Caching: The package does not cache logs by default, but you could extend it to cache frequent queries (e.g., Activity::latest()).
  • Testing: The package includes comprehensive tests. Ensure your CI pipeline runs composer test to catch regressions.

Sequencing

  1. Prerequisites:
    • Laravel application with Eloquent models.
    • Database with write permissions for the new activity_log table.
    • Composer access to install the package.
  2. Installation:
    composer require spatie/laravel-activitylog
    php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"
    php artisan migrate
    
  3. Configuration:
    • Publish the config file (optional):
      php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-config"
      
    • Customize config/activitylog.php if needed (e.g., default_log_name).
  4. Model Integration:
    • Add use LogsActivity; to target models.
    • Override getActivitylogOptions() for custom behavior.
  5. Manual Logging:
    • Replace ad-hoc logging (e.g., Log::info()) with activity()->log() where appropriate.
  6. Hooks and Resolvers:
    • Register beforeLogging callbacks in a service provider (e.g., AppServiceProvider).
    • Configure CauserResolver if default user resolution isn’t sufficient.
  7. Monitoring:
    • Set up alerts for activity_log table growth or slow queries.
    • Implement a dashboard (e.g., Laravel Nova, custom admin panel) to query logs.

Operational Impact

Maintenance

  • Package Updates:
    • The package is actively maintained (last release: 2026-03-25). Follow the UPGRADING guide for major version changes.
    • Monitor the GitHub Issues for breaking changes
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony