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

garcia1901l/laravel-activity-lite

Lightweight MongoDB-backed activity logger for Laravel (7–12). Automatically tracks model create/update/delete, records the causer (user, artisan, queues), supports manual log entries, configurable events, and powerful querying with CLI filters and JSON/CSV export.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require garcia1901l/laravel-activity-lite
    php artisan activity-lite:install
    
    • This sets up the MongoDB connection and publishes the config file if needed.
  2. Enable Tracking for a Model: Add the ActivityTrait to your Eloquent model:

    use Garcia1901l\LaravelActivityLite\Traits\ActivityTrait;
    
    class Post extends Model
    {
        use ActivityTrait;
    }
    
    • No additional configuration is required for basic tracking (creates, updates, deletes).
  3. First Use Case: Log an activity manually (e.g., in a controller or observer):

    use Garcia1901l\LaravelActivityLite\Facades\ActivityLite;
    
    ActivityLite::log('post.updated', $post, 'Custom description');
    
    • Query activities:
    $activities = ActivityLite::query()
        ->whereModel('App\Models\Post')
        ->whereEvent('post.updated')
        ->get();
    

Implementation Patterns

Core Workflows

  1. Automatic Model Tracking:

    • Enable for any model by adding ActivityTrait. The package auto-logs created, updated, and deleted events.
    • Customize tracked events via the activityEvents property:
      protected $activityEvents = ['created', 'updated', 'deleted', 'published'];
      
  2. Manual Logging:

    • Log custom events with context:
      ActivityLite::log('user.login', $user, 'Logged in via API', ['ip' => $request->ip()]);
      
    • Useful for non-model events (e.g., API calls, CLI commands).
  3. Querying Activities:

    • Chain query methods for filtering:
      ActivityLite::query()
          ->whereModel('App\Models\User')
          ->whereEvent('user.login')
          ->whereCauser('admin@test.com')
          ->orderBy('created_at', 'desc')
          ->limit(10)
          ->get();
      
    • Retrieve a single activity:
      $activity = ActivityLite::query()->first();
      
  4. Integration with Observers/Events:

    • Extend existing observers to log activities:
      public function saving(Model $model)
      {
          if ($model->isDirty('status')) {
              ActivityLite::log('post.status_changed', $model);
          }
      }
      
  5. Causer Tracking:

    • Automatically captures the user/agent responsible for the activity (e.g., auth()->user() or app()->runningInConsole()).
    • Override manually if needed:
      ActivityLite::log('manual.event', $model, null, null, 'custom_causer@example.com');
      

Advanced Patterns

  1. Activity Scopes:

    • Create reusable query scopes in a service class:
      class ActivityScopes
      {
          public static function recent($days = 7)
          {
              return ActivityLite::query()
                  ->where('created_at', '>=', now()->subDays($days));
          }
      }
      
  2. Batch Processing:

    • Log activities in bulk (e.g., during imports):
      ActivityLite::logBatch([
          ['event' => 'import.started', 'model' => $model, 'description' => 'Bulk import'],
          ['event' => 'items.created', 'model' => $model, 'count' => 100],
      ]);
      
  3. Activity-Based Notifications:

    • Trigger notifications from activity logs:
      $activities = ActivityLite::query()
          ->whereEvent('order.paid')
          ->where('created_at', '>=', now()->subHours(1))
          ->get();
      
      foreach ($activities as $activity) {
          Notification::send($activity->causer, new OrderPaid($activity));
      }
      

Gotchas and Tips

Pitfalls

  1. MongoDB Connection:

    • Ensure mongodb/laravel-mongodb is installed and configured in .env:
      MONGO_CONNECTION=default
      MONGO_DATABASE=activity_lite
      
    • If using a custom MongoDB driver version, manually specify it in composer.json to avoid conflicts.
  2. Causer Resolution:

    • The package defaults to auth()->user() for web requests and app()->runningInConsole() for CLI. Override in config/activity-lite.php if your auth system differs:
      'causer_resolver' => function () {
          return auth('api')->user() ?? 'system';
      },
      
  3. Event Naming:

    • Use dot notation for events (e.g., user.profile.updated) to avoid collisions. Avoid spaces or special characters.
  4. Performance:

    • Avoid logging excessively granular events (e.g., property.changed for every field update). Batch or debounce logs where possible.
    • Index frequently queried fields in MongoDB (e.g., event, model, created_at).
  5. Model Serialization:

    • Large models may bloat activity logs. Use activityAttributes to limit logged fields:
      protected $activityAttributes = ['id', 'title', 'status'];
      

Debugging

  1. Log Inspection:

    • Dump raw activity logs for debugging:
      dd(ActivityLite::query()->get()->toArray());
      
    • Check MongoDB directly if queries behave unexpectedly:
      mongosh --eval 'db.activity_lite.find().pretty()'
      
  2. Common Issues:

    • "Table not found": Verify MongoDB is running and the activity_lite collection exists (run php artisan activity-lite:install again).
    • Missing causer: Ensure your auth system is properly bootstrapped before logging activities.
    • Query timeouts: Optimize queries with select(), where(), or limit() to avoid fetching large datasets.

Extension Points

  1. Custom Activity Model:

    • Extend the default Activity model to add fields:
      namespace App\Models;
      
      use Garcia1901l\LaravelActivityLite\Models\Activity as BaseActivity;
      
      class Activity extends BaseActivity
      {
          protected $casts = [
              'metadata' => 'array',
              'tags' => 'array',
          ];
      }
      
    • Update the config to use your model:
      'model' => App\Models\Activity::class,
      
  2. Activity Events:

    • Listen for activity creation to trigger side effects:
      ActivityLite::created(function ($activity) {
          if ($activity->event === 'user.created') {
              // Send welcome email
          }
      });
      
  3. Middleware for API Tracking:

    • Log API requests automatically:
      public function handle($request, Closure $next)
      {
          $response = $next($request);
          ActivityLite::log(
              'api.request',
              null,
              $request->method() . ' ' . $request->path(),
              ['ip' => $request->ip(), 'user_agent' => $request->userAgent()]
          );
          return $response;
      }
      
  4. Activity Exporters:

    • Export logs to CSV/JSON for audits:
      $activities = ActivityLite::query()
          ->where('created_at', '>=', now()->subDays(30))
          ->get()
          ->toArray();
      
      file_put_contents('activity_log.json', json_encode($activities));
      
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
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