Weave 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

Activity Laravel Package

chill-project/activity

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chill-project/activity
    

    Ensure your project uses Symfony Flex auto-configuration (Laravel 5.5+) or manually register the bundle in config/app.php under providers.

  2. Publish Configuration

    php artisan vendor:publish --provider="Chill\ActivityBundle\ActivityBundle" --tag="config"
    

    This generates config/activity.php. Review and adjust default settings (e.g., activity_model, activity_table).

  3. First Activity Log Inject the ActivityManager service into a controller or service:

    use Chill\ActivityBundle\Manager\ActivityManager;
    
    public function __construct(private ActivityManager $activityManager) {}
    
    public function logExample() {
        $this->activityManager->log('user.created', 'User #123 was created', ['user_id' => 123]);
    }
    
  4. Verify Check the database table (default: activities) for the logged entry.


Key Files to Review

  • Config: config/activity.php (adjust table names, models, or logging behavior).
  • Manager: src/Manager/ActivityManager.php (core logging interface).
  • Models: src/Entity/Activity.php (customize if extending the default model).

Implementation Patterns

Core Workflow: Logging Activities

  1. Basic Logging

    $this->activityManager->log(
        'event.name',          // Event name (string)
        'Human-readable text', // Description
        ['metadata' => 'value'] // Optional associative array
    );
    
    • Use semantic event names (e.g., user.login.failed, order.paid).
    • Keep descriptions concise but meaningful (visible in admin panels).
  2. Bulk Logging For batch operations (e.g., importing users):

    $this->activityManager->logBulk([
        ['event' => 'user.imported', 'description' => 'Imported 100 users', 'data' => [...]],
        // ... more entries
    ]);
    
  3. Conditional Logging Use middleware or decorators to filter activities:

    if ($user->isAdmin()) {
        $this->activityManager->log('admin.action', 'Performed X', ['user_id' => $user->id]);
    }
    

Integration Tips

  1. Laravel-Specific

    • Service Provider Binding: Override the default manager in AppServiceProvider:
      $this->app->bind(ActivityManager::class, function ($app) {
          return new CustomActivityManager($app->make(ActivityRepository::class));
      });
      
    • Event Listeners: Trigger activities from Laravel events:
      use Illuminate\Auth\Events\Registered;
      
      Registered::listen(function ($event) {
          $event->user->activity()->log('user.registered');
      });
      
  2. Database Optimization

    • Indexing: Add indexes to event, description, and data columns for queries:
      Schema::table('activities', function (Blueprint $table) {
          $table->index('event');
          $table->index('created_at');
      });
      
    • Archiving: Implement a cron job to archive old activities (e.g., >6 months) to a separate table.
  3. API Responses Expose activities via API:

    Route::get('/activities', function (ActivityManager $manager) {
        return response()->json($manager->findAll()->toArray());
    });
    
  4. Frontend Integration

    • Admin Panels: Use the data to build audit logs (e.g., with Laravel Nova or Filament).
    • Real-Time Updates: Push activity logs to frontend via Laravel Echo/Pusher for live dashboards.

Gotchas and Tips

Pitfalls

  1. Performance

    • Bulk Logging Overhead: Avoid logging thousands of entries in a single logBulk call. Batch in chunks of 100–500.
    • Database Locks: High-frequency logging may cause table locks. Consider queueing activities:
      $this->activityManager->logQueued('event.name', 'Description');
      
  2. Data Serialization

    • The data field is JSON-encoded. Ensure all values are serializable (avoid closures, resources).
    • Tip: Use json_encode($data, JSON_THROW_ON_ERROR) to catch non-serializable data early.
  3. Model Customization

    • If extending Activity model, override fillable to control which fields can be mass-assigned:
      protected $fillable = ['event', 'description', 'data', 'metadata'];
      
  4. Event Collisions

    • Reuse event names sparingly. Prefer namespaced events (e.g., invoice.created vs. created).

Debugging

  1. Missing Logs

    • Check if the Activity model/table exists and is properly configured in config/activity.php.
    • Verify the ActivityManager is bound correctly (no service provider conflicts).
  2. Query Issues

    • Use Activity::query()->toSql() to inspect generated queries.
    • Enable Laravel debugging (APP_DEBUG=true) to see raw SQL.
  3. Data Corruption

    • The data field may corrupt if non-serializable data is passed. Validate inputs:
      try {
          json_encode($data);
      } catch (JsonException $e) {
          throw new \InvalidArgumentException('Activity data must be JSON-serializable');
      }
      

Extension Points

  1. Custom Activity Types Extend the Activity model to add fields:

    class CustomActivity extends Activity
    {
        protected $casts = [
            'ip_address' => 'string',
            'user_agent' => 'text',
        ];
    }
    

    Update the migration and config accordingly.

  2. Activity Filters Add scopes to the Activity model for common queries:

    public function scopeForUser($query, $userId)
    {
        return $query->whereJsonContains('data->user_id', $userId);
    }
    
  3. Activity Subscribers Listen for activity events to trigger side effects:

    Activity::created(function ($activity) {
        if ($activity->event === 'user.suspended') {
            // Send email, revoke API keys, etc.
        }
    });
    
  4. Testing Mock the ActivityManager in tests:

    $mockManager = Mockery::mock(ActivityManager::class);
    $mockManager->shouldReceive('log')
        ->once()
        ->with('test.event', 'Test description', ['key' => 'value']);
    $this->app->instance(ActivityManager::class, $mockManager);
    
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.
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
frankyso/ipaymu
3mdikram/worldmoneywords
snowsoft/config
itmosoft/laravel-subscriptions
larva/laravel-ai-qwen
adachsoft/api-version-bundle