arpanihan/auditify

A powerful, intuitive, and efficient action and activity log tracking package for Laravel applications.

1.0.0 2025-08-23 08:12 UTC

This package is not auto-updated.

Last update: 2025-08-23 11:54:31 UTC


README

Auditify is a flexible and easy-to-use package for Laravel that allows you to log Action Logs (system-level actions like CRUD operations) and Activity Logs (frontend user interactions like page visits, button clicks, etc.). The package is highly configurable and can be easily integrated into any Laravel project.

✨ Key Features

  • οΏ½ Action Logging: Track system-level operations (CRUD actions, logins, etc.)
  • πŸ‘† Activity Logging: Monitor user interactions (page visits, button clicks, tab switches)
  • 🎯 Frontend JavaScript Integration: Automatic frontend activity tracking
  • βš™οΈ Fully Configurable: Customize table names, log types, pagination via config
  • πŸ›‘οΈ Safe Installation: No foreign key constraints, configurable table names
  • πŸ“Š API Ready: JSON endpoints for custom frontends
  • πŸš€ Laravel 9+ Compatible: Works with modern Laravel versions

οΏ½ Requirements

  • PHP >= 8.0
  • Laravel >= 9.0
  • Composer

πŸš€ Installation

🟒 Recommended: Safe Installation (All Projects)

# Step 1: Install package
composer require arpanihan/auditify

# Step 2: Safe installation with built-in checks
php artisan auditify:install

This command will:

  • βœ… Check for table conflicts before creating anything
  • βœ… Publish config with safe defaults
  • βœ… Run only Auditify migrations (not your existing ones)
  • βœ… Publish assets safely
  • βœ… Provide clear feedback on each step

πŸ” Check Installation Status

# Check if everything is properly installed
php artisan auditify:status

🟑 Alternative: Manual Installation (Advanced Users)

If you prefer manual control or need specific migration paths:

# Install package
composer require arpanihan/auditify

# Publish config and customize table names if needed
php artisan vendor:publish --tag=auditify-config

# Edit config/auditify.php to customize table names for your project
# Then publish migrations
php artisan vendor:publish --tag=auditify-migrations

# This will create migrations with timestamps like:
# database/migrations/YYYY_MM_DD_HHMMSS_create_auditify_action_logs_table.php
# database/migrations/YYYY_MM_DD_HHMMSS_create_auditify_activity_logs_table.php

# List exact migration file names
php artisan auditify:migrations list

# Run ONLY the Auditify migrations (replace with actual filenames)
php artisan migrate --path=database/migrations/2024_08_23_131452_create_auditify_action_logs_table.php
php artisan migrate --path=database/migrations/2024_08_23_131452_create_auditify_activity_logs_table.php

# Publish assets
php artisan vendor:publish --tag=auditify-assets

πŸ“‹ Get Specific Migration Paths

# See all Auditify migration commands and paths
php artisan auditify:migrations list

# This shows exact file names and commands for your project

πŸ”΄ ❌ AVOID: Full Migration Command

⚠️ DO NOT USE in existing projects:

php artisan migrate  # This runs ALL migrations, can be dangerous!

Instead use:

php artisan auditify:install  # Safe installation

βš™οΈ Configuration

The package comes with a comprehensive configuration file. After publishing, you can modify config/auditify.php:

return [
    // Activity logging options
    'activity' => [
        'enabled' => true,
        'events' => [
            'page_visit' => true,
            'tab_switch' => true,
            'modal_open' => true,
            'button_click' => true,
        ],
        'js_path' => '/vendor/auditify/js/activityLog.js',
    ],

    // Action logging options
    'action' => [
        'enabled' => true,
        'modules' => ['user', 'product', 'order', 'report'],
    ],

    // Database settings
    'database' => [
        'check_existing_tables' => true,
        'use_foreign_keys' => false,
    ],

    // Table names (customize to avoid conflicts)
    'tables' => [
        'activity_logs' => env('AUDITIFY_ACTIVITY_TABLE', 'auditify_activity_logs'),
        'action_logs'   => env('AUDITIFY_ACTION_TABLE', 'auditify_action_logs'),
    ],

    // Pagination and retention
    'pagination' => [
        'activity_log_limit' => 50,
        'action_log_limit'   => 50,
    ],
    'retention_days' => 365,
];

Environment Variables

You can also use environment variables in your .env file:

AUDITIFY_ENABLE_ROUTES=true
AUDITIFY_ACTIVITY_TABLE=my_custom_activity_logs
AUDITIFY_ACTION_TABLE=my_custom_action_logs

Running Migrations

After publishing the migration files, you can run the migrations for Auditify separately from your existing migrations to avoid conflicts with your project’s database.

To run only the Auditify migrations, use the following command:

php artisan migrate --path=/database/migrations/your_auditify_migration_folder

This will apply only the Auditify migrations and will not interfere with any other migrations in your project. Ensure that your_auditify_migration_folder points to the correct folder where Auditify migrations are located.

If you want to run all migrations, including your project migrations, simply use:

php artisan migrate

However, we recommend running the package-specific migrations to avoid any issues.

Configuration

After publishing the config file, you can modify the config/auditify.php file to suit your needs.

Example Configuration (config/auditify.php):

return [

    /*
    |--------------------------------------------------------------------------
    | Activity Log Options
    |--------------------------------------------------------------------------
    |
    | Options for ActivityLogger. External users can enable/disable certain events.
    | Example: Page visits, Tab switches, Modal opens, Button clicks.
    |
    */
    'activity' => [
        'enabled' => true, // Enable/Disable activity logging
        'events' => [
            'page_visit' => true, // Log page visits
            'tab_switch' => true,  // Log tab switches
            'modal_open' => true,  // Log modal openings
            'button_click' => true, // Log button clicks
        ],
        'js_path' => '/vendor/auditify/js/activityLog.js', // Path for the frontend activity logger JS file
    ],

    /*
    |--------------------------------------------------------------------------
    | Action Log Options
    |--------------------------------------------------------------------------
    |
    | Options for ActionLogger. Mainly for CRUD/system operations.
    | You can enable/disable specific modules if needed.
    |
    */
    'action' => [
        'enabled' => true, // Enable/Disable action logging
        'modules' => [
            'user', 'product', 'order', 'report', // Default modules for logging (can be modified)
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | General Options
    |--------------------------------------------------------------------------
    |
    | Default values for table names, pagination, and log retention.
    |
    */
    'tables' => [
        'activity_logs' => 'activity_logs', // Table name for activity logs
        'action_logs'   => 'action_logs',   // Table name for action logs
    ],

    'pagination' => [
        'activity_log_limit' => 50, // Default limit for activity log pagination
        'action_log_limit'   => 50, // Default limit for action log pagination
    ],

    'retention_days' => 365, // Optionally auto-delete older logs after this number of days
];

Dynamic Configuration

  • Activity Log Events: You can enable or disable specific events like page visits, tab switches, modal openings, and button clicks.
  • Action Log Modules: Specify the modules you want to track, such as user, product, order, report. Add or remove modules as needed.
  • Table Names: You can customize the table names for both activity logs and action logs.
  • Pagination: Adjust the number of logs per page using the pagination section.
  • Log Retention: Optionally delete older logs after a specified number of days (e.g., after 365 days).

πŸ“š Usage

Action Logging

Log system-level operations like CRUD actions, logins, etc:

use ArpaNihan\Auditify\Services\ActionLogger;

// Basic usage
ActionLogger::log('created', 'User created a new post', null, 'Posts');

// With all parameters
ActionLogger::log(
    action: 'updated',
    message: 'Post title was updated',
    url: request()->fullUrl(),
    module: 'Posts',
    user_id: auth()->id(),
    user_name: auth()->user()->name,
    user_role: auth()->user()->role
);

// Examples of different actions
ActionLogger::log('login', 'User logged in successfully', null, 'Authentication');
ActionLogger::log('deleted', 'Product #123 was deleted', null, 'Products');
ActionLogger::log('exported', 'Generated sales report', null, 'Reports');

Activity Logging

Log user interactions and frontend activities:

use ArpaNihan\Auditify\Services\ActivityLogger;

// Basic usage
ActivityLogger::log('page_visit', 'User visited dashboard', null, 'Dashboard');

// Common activity examples
ActivityLogger::log('tab_switch', 'Switched to settings tab', null, 'Settings');
ActivityLogger::log('modal_open', 'Opened user profile modal', null, 'Users');

Frontend JavaScript Integration

Automatically track frontend activities with the included JavaScript module:

<!-- Add meta tags to your layout -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="user-id" content="{{ auth()->id() }}">
<meta name="user-name" content="{{ auth()->user()->name }}">
<meta name="user-role" content="{{ auth()->user()->role }}">

<!-- Include the activity logger -->
<script type="module">
    import { logActivity } from '{{ asset(config("auditify.activity.js_path")) }}';

    // Auto-log page visits
    const path = window.location.pathname;
    const moduleGuess = path.split('/')[1] || 'Dashboard';
    
    if (!path.includes('/activity-log')) {
        logActivity('Page Visit', `Visited ${document.title}`, moduleGuess);
    }

    // Auto-log tab switches
    document.querySelectorAll('[data-bs-toggle="tab"]').forEach(tab => {
        tab.addEventListener("shown.bs.tab", function (e) {
            logActivity("Tab Switch", `Switched to: ${e.target.textContent.trim()}`, moduleGuess);
        });
    });

    // Auto-log modal opens
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener("show.bs.modal", function (e) {
            logActivity("Modal Opened", `Opened: ${e.target.id}`, moduleGuess);
        });
    });

    // Auto-log button clicks
    document.querySelectorAll('button:not([type="submit"])').forEach(btn => {
        btn.addEventListener("click", function () {
            const label = btn.innerText.trim() || btn.getAttribute('title') || 'Unnamed';
            logActivity("Button Click", `Clicked: ${label}`, moduleGuess);
        });
    });
</script>

Using Facades

You can also use the package facades for cleaner code:

use ArpaNihan\Auditify\Facades\Auditify;

// Using facade (registers as 'auditify' service)
app('auditify')->log('created', 'New user registered', null, 'Users');
app('activitylog')->log('page_visit', 'Visited profile page', null, 'Profile');

πŸ”— API Endpoints

The package provides API endpoints for external integrations:

# Get action logs (JSON)
GET /auditify/api/action-logs

# Log activity via AJAX
POST /log-activity

πŸ› οΈ Troubleshooting

Common Issues & Solutions

❌ "Table already exists" Error

Problem: Migration fails because table names conflict with existing tables.

Solution:

# Option 1: Use the safe install command (recommended)
php artisan auditify:install

# Option 2: Customize table names
# Edit config/auditify.php and change table names:
'tables' => [
    'activity_logs' => 'my_app_activity_logs',
    'action_logs'   => 'my_app_action_logs',
],

❌ "Migration ran all my migrations"

Problem: Used php artisan migrate instead of safe installation.

Solution:

# Always use the safe installation:
php artisan auditify:install

# Or get specific migration paths and run individually:
php artisan auditify:migrations list

# Then run specific migrations shown in the list:
php artisan migrate --path=database/migrations/YYYY_MM_DD_HHMMSS_create_auditify_action_logs_table.php
php artisan migrate --path=database/migrations/YYYY_MM_DD_HHMMSS_create_auditify_activity_logs_table.php

❌ "Config not found" Error

Problem: Configuration file not published.

Solution:

php artisan vendor:publish --tag=auditify-config
# Or use the complete installation:
php artisan auditify:install

❌ JavaScript not working

Problem: Assets not published.

Solution:

php artisan vendor:publish --tag=auditify-assets
# Or check installation status:
php artisan auditify:status

Quick Commands Reference

# Check installation status
php artisan auditify:status

# Safe installation
php artisan auditify:install

# Force installation (skip safety checks)
php artisan auditify:install --force

# List migration paths and commands
php artisan auditify:migrations list

# Publish migrations only
php artisan auditify:migrations publish

# Run migrations only
php artisan auditify:migrations run

# Publish specific components
php artisan vendor:publish --tag=auditify-config
php artisan vendor:publish --tag=auditify-migrations  
php artisan vendor:publish --tag=auditify-assets

πŸ§ͺ Testing

The package is thoroughly tested. Run tests in your Laravel project:

# Run package-specific tests
php artisan test tests/Feature/AuditifyIntegrationTest.php

# Or create your own tests
php artisan make:test AuditifyCustomTest

Example Test

use ArpaNihan\Auditify\Services\ActionLogger;

public function test_action_logging_works()
{
    ActionLogger::log('test_action', 'Testing action logging', null, 'Tests');
    
    $this->assertDatabaseHas('auditify_action_logs', [
        'action' => 'test_action',
        'message' => 'Testing action logging',
        'module' => 'Tests'
    ]);
}

ActivityLogger::log('tab_switch', 'Switched to settings tab', null, 'Settings'); ActivityLogger::log('modal_open', 'Opened user profile modal', null, 'Users');

Logging an Activity

To log user activities (e.g., page visits, button clicks, etc.), use the ActivityLogger service.

use ArpaNihan\Auditify\Services\ActivityLogger;

ActivityLogger::log(
    'visited',  // Action (e.g., 'visited', 'clicked', etc.)
    'User visited the dashboard',  // Message
    'http://example.com/dashboard',  // URL (optional)
    'DashboardModule',  // Module name (optional)
);

Frontend Activity Logging (JavaScript)

The Auditify package includes a JavaScript file (activityLog.js) for logging frontend activities. You can include it in your Blade views.

Example Usage:

<script type="module">
    import { logActivity } from '{{ asset(config("auditify.activity.js_path")) }}';

    const path = window.location.pathname;
    const moduleGuess = path.split('/')[1] || 'Dashboard';

    // Log page visit
    if (!path.includes('/admin/activity-log')) {
        logActivity('Page Visit', `Visited ${document.title}`, moduleGuess);
    }

    // Log tab switch
    document.querySelectorAll('[data-bs-toggle="tab"]').forEach(tab => {
        tab.addEventListener("shown.bs.tab", function (e) {
            logActivity("Tab Switch", `Switched to tab: ${e.target.textContent.trim()}`, moduleGuess);
        });
    });

    // Log modal opened
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener("show.bs.modal", function (e) {
            logActivity("Modal Opened", `Opened modal: ${e.target.id}`, moduleGuess);
        });
    });

    // Log button clicks
    document.querySelectorAll('button:not([type="submit"])').forEach(btn => {
        btn.addEventListener("click", function () {
            const label = btn.innerText.trim() || btn.getAttribute('title') || 'Unnamed';
            logActivity("Button Click", `Clicked: ${label}`, moduleGuess);
        });
    });
</script>

Customizing the JavaScript Path

If you prefer to use a custom path for the activityLog.js file, simply modify the activity_js_path key in config/auditify.php.

πŸ”§ Advanced Configuration

Custom Table Names

Avoid conflicts by customizing table names in your .env file:

AUDITIFY_ACTIVITY_TABLE=my_app_activity_logs
AUDITIFY_ACTION_TABLE=my_app_action_logs

Disabling Routes

If you want to use only the logging functionality without web routes:

AUDITIFY_ENABLE_ROUTES=false

Role Resolution

The package safely resolves user roles. If you have a custom Role model:

// The package will automatically try to resolve roles if App\Models\Role exists
// No additional configuration needed

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“„ License

This package is open-sourced software licensed under the MIT license.

πŸ‘¨β€πŸ’» Author

ArpaNihan

πŸ“Š Package Stats

  • Minimum PHP: 8.0+
  • Laravel Compatibility: 9.0+
  • Dependencies: Minimal (only illuminate/support)
  • Database: MySQL, PostgreSQL, SQLite compatible
  • File Size: Lightweight package

Ready to track every action in your Laravel app? Install Auditify today! πŸš€