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

cetiia/laravel-activity-log

Laravel package that automatically records application activity to a logs table after migration and provides an activity-log route to view entries. Includes publishable migrations and optional views; access to the route can be protected via a Gate in AuthServiceProvider.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cetiia/laravel-activity-log
    

    Publish the migration and config:

    php artisan vendor:publish --provider="Cetiia\ActivityLog\ActivityLogServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="Cetiia\ActivityLog\ActivityLogServiceProvider" --tag="config"
    

    Run the migration:

    php artisan migrate
    
  2. Basic Usage Log an activity for a model (e.g., User):

    use Cetiia\ActivityLog\ActivityLog;
    
    // Log a custom event
    ActivityLog::log('user.created', 'User created', ['user_id' => 1]);
    
    // Log model events (e.g., created, updated, deleted)
    ActivityLog::logModelEvent('user', 'created', ['user_id' => 1]);
    
  3. First Use Case Track user sign-ups and admin actions:

    // In UserObserver or controller
    ActivityLog::log('auth.login', 'User logged in', ['user_id' => auth()->id()]);
    

Implementation Patterns

Model Observers

Leverage Laravel’s observers to auto-log model events:

// app/Observers/UserObserver.php
public function created(User $user)
{
    ActivityLog::logModelEvent('user', 'created', ['user_id' => $user->id]);
}

Middleware for API/Controller Logging

Log API requests or controller actions:

// app/Http/Middleware/LogActivity.php
public function handle($request, Closure $next)
{
    ActivityLog::log('api.request', $request->method() . ' ' . $request->path(), [
        'ip' => $request->ip(),
        'user_id' => auth()->id(),
    ]);
    return $next($request);
}

Query Builder Integration

Log database queries (e.g., for auditing):

// Before a critical query
ActivityLog::log('query.executed', 'Fetching users', ['query' => $query->toSql()]);
$users = User::where('active', true)->get();

Event Listeners

Attach to Laravel events (e.g., illuminate\auth\events\Registered):

// app/Listeners/LogUserRegistration.php
public function handle($event)
{
    ActivityLog::log('user.registered', 'New user registered', ['email' => $event->user->email]);
}

Custom Log Types

Extend the package for domain-specific logs:

// app/Services/CustomActivityLogger.php
class CustomActivityLogger
{
    public static function logPayment($paymentId, $amount, $status)
    {
        ActivityLog::log('payment.processed', "Payment {$status}", [
            'payment_id' => $paymentId,
            'amount' => $amount,
        ]);
    }
}

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Avoid logging in loops or high-frequency operations. Use batching or queues for bulk actions.
    • Example: Log only the first/last item in a loop:
      $users = User::all();
      ActivityLog::log('batch.processed', 'Processed ' . count($users) . ' users', ['batch_id' => uniqid()]);
      
  2. Missing Model Events

    • Ensure observers are registered in AppServiceProvider:
      User::observe(UserObserver::class);
      
  3. Config Quirks

    • The activity_log table name is configurable in config/activity-log.php. Update if using a custom schema.
  4. Debugging Logs

    • Check the activity_logs table directly or use:
      $logs = \Cetiia\ActivityLog\Models\ActivityLog::latest()->take(10)->get();
      

Extension Points

  1. Custom Fields Add columns to the activity_logs table via migration:

    Schema::table('activity_logs', function (Blueprint $table) {
        $table->string('metadata')->nullable();
    });
    
  2. Log Filtering Filter logs by type or properties in queries:

    $logs = ActivityLog::where('type', 'user.created')->where('properties->user_id', 1)->get();
    
  3. Soft Deletes Enable soft deletes in the ActivityLog model if needed:

    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class ActivityLog extends Model
    {
        use SoftDeletes;
        protected $dates = ['deleted_at'];
    }
    
  4. Queue Integration Offload logging to a queue for async processing:

    ActivityLog::dispatch('user.created')->toQueue('activity-logs');
    

    Requires extending the ActivityLog facade or service provider.

Tips

  • Use Descriptive Types: Prefix log types (e.g., auth.login, payment.refunded) for clarity.
  • Sanitize Data: Avoid logging sensitive data (e.g., passwords, tokens). Use hashes or masks.
  • Retention Policy: Add a deleted_at column and a scheduled job to purge old logs:
    // app/Console/Commands/CleanupActivityLogs.php
    public function handle()
    {
        \Cetiia\ActivityLog\Models\ActivityLog::where('created_at', '<', now()->subDays(30))->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