PHPackages                             iamfarhad/laravel-audit-log - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. iamfarhad/laravel-audit-log

ActiveLibrary[Database &amp; ORM](/categories/database)

iamfarhad/laravel-audit-log
===========================

Comprehensive entity-level audit logging package for Laravel applications with model-specific tables, field exclusion, and batch processing support

1.6.0(5mo ago)1315.6k↓11.3%8[1 issues](https://github.com/iamfarhad/laravel-audit-log/issues)[1 PRs](https://github.com/iamfarhad/laravel-audit-log/pulls)MITPHPPHP ^8.1

Since May 28Pushed 5mo agoCompare

[ Source](https://github.com/iamfarhad/laravel-audit-log)[ Packagist](https://packagist.org/packages/iamfarhad/laravel-audit-log)[ RSS](/packages/iamfarhad-laravel-audit-log/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (13)Used By (0)

Laravel Audit Logger
====================

[](#laravel-audit-logger)

[![Latest Version on Packagist](https://camo.githubusercontent.com/9550a97c607eaf911292cca6953aacfa12805b978ecc23f4b7cc4f131666e1af/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f69616d6661726861642f6c61726176656c2d61756469742d6c6f672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iamfarhad/laravel-audit-log)[![Total Downloads](https://camo.githubusercontent.com/5ccd9bfca8cc39f29ebed1b52e99a39d67127b6012ff9e3afec8bdc371247e5c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f69616d6661726861642f6c61726176656c2d61756469742d6c6f672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iamfarhad/laravel-audit-log)[![PHP Version](https://camo.githubusercontent.com/c3d372b55ac2d4fcf386a178e11d9788310097b35f3893cf3daae574b6b4cd3e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d626c75652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iamfarhad/laravel-audit-log)[![Laravel Version](https://camo.githubusercontent.com/29cb03e17c7c1b807aa63aa7c0e0e9824f15868ca6649e0985ff20d7844607f7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302e7825374331312e7825374331322e782d7265642e7376673f7374796c653d666c61742d737175617265)](https://laravel.com/)[![GitHub stars](https://camo.githubusercontent.com/e68cef529f52844c28bedc62f9ebbf43bc89f0a1e49e65117937ab8464176c0f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f69616d6661726861642f6c61726176656c2d61756469742d6c6f672e7376673f7374796c653d666c61742d737175617265)](https://github.com/iamfarhad/laravel-audit-log/stargazers)

[![License](https://camo.githubusercontent.com/1625f7581dda8dbc0d3b5443884f484e3ab6f37476e2bf6eaa25ec14d5290f3f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f69616d6661726861642f6c61726176656c2d61756469742d6c6f672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/iamfarhad/laravel-audit-log)[![Maintained](https://camo.githubusercontent.com/d30bad569de5ac6d355cd83d992851fd2d84a6fc4dc1bcca7f4d6ccbfd87cdb7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d61696e7461696e65642d7965732d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/iamfarhad/laravel-audit-log)[![Tests](https://camo.githubusercontent.com/22ad7d9c36c77be3a74c6a49b23363eafb4513a3603cb1949b65016169be07b9/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f69616d6661726861642f6c61726176656c2d61756469742d6c6f672f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/iamfarhad/laravel-audit-log/actions/workflows/tests.yml)[![Code Style](https://camo.githubusercontent.com/0b60fbc443d9f4471c61ad241a42f6c75db6ed60a0a71ff892bf50a0a46a7165/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f69616d6661726861642f6c61726176656c2d61756469742d6c6f672f636f64696e672d7374616e64617264732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/iamfarhad/laravel-audit-log/actions/workflows/coding-standards.yml)[![PHPStan](https://camo.githubusercontent.com/4470f8df20a6d13b9eac69d9a1f3abcd72eb30f8436f5355e69f06cb6bd970ab/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230352d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/iamfarhad/laravel-audit-log)

Overview
--------

[](#overview)

**Laravel Audit Logger** is a powerful and flexible package designed to provide comprehensive audit logging for Laravel applications. It enables tracking of all changes to your Eloquent models with advanced features including source tracking, queue processing, and customizable field management, ensuring compliance with regulatory requirements, aiding in debugging, and maintaining data integrity. Built with modern PHP and Laravel practices, this package adheres to strict typing, PSR-12 coding standards, and leverages dependency injection for maximum testability and maintainability.

The package uses a high-performance direct logging architecture with optional queue integration, making it suitable for both small applications and enterprise-scale systems.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
    - [Basic Usage](#basic-usage)
    - [Advanced Usage](#advanced-usage)
    - [Source Tracking](#source-tracking)
    - [Queue Processing](#queue-processing)
- [Customizing Audit Logging](#customizing-audit-logging)
- [Retrieving Audit Logs](#retrieving-audit-logs)
- [Performance Optimization](#performance-optimization)
- [Testing](#testing)
- [Security Best Practices](#security-best-practices)
- [Audit Log Retention](#audit-log-retention)
- [Migration &amp; Upgrade Guide](#migration--upgrade-guide)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)

Features
--------

[](#features)

- **Entity-Specific Audit Tables**: Automatically creates dedicated tables for each audited model to optimize performance and querying.
- **Comprehensive Change Tracking**: Logs all CRUD operations (create, update, delete, restore) with old and new values.
- **Advanced Source Tracking**: Automatically tracks the source of changes (console commands, HTTP routes, background jobs) for enhanced debugging and compliance.
- **Queue Processing**: Supports both synchronous and asynchronous audit log processing for improved performance.
- **Customizable Field Management**: Control which fields to include or exclude from auditing with global and model-specific configurations.
- **User Tracking**: Automatically identifies and logs the user (causer) responsible for changes with configurable guard and resolver support.
- **Direct Logging Architecture**: Uses direct service calls for high-performance logging with optional event integration.
- **Batch Processing**: Supports batch operations for high-performance logging in large-scale applications.
- **Type Safety**: Built with PHP 8.1+ strict typing, readonly properties, and modern features.
- **Enhanced Query Scopes**: Comprehensive filtering capabilities with dedicated scopes for different query patterns.
- **Extensible Drivers**: Supports multiple storage drivers (currently MySQL) with the ability to implement custom drivers.
- **Automatic Migration**: Seamlessly creates audit tables for new models when enabled.
- **Smart Retention System**: Comprehensive retention policies with delete, anonymize, and archive strategies for compliance and performance.
- **Static Analysis**: Level 5 PHPStan compliance for maximum code quality and reliability.

Requirements
------------

[](#requirements)

- **PHP**: 8.1 or higher
- **Laravel**: 10.x, 11.x, or 12.x
- **Database**: MySQL 8.0+ (for the default driver)

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require iamfarhad/laravel-audit-log
```

After installation, publish the configuration file to customize settings:

```
php artisan vendor:publish --tag=audit-logger-config
```

This will create a configuration file at `config/audit-logger.php` where you can adjust settings like the storage driver, table naming conventions, queue processing, and more.

Configuration
-------------

[](#configuration)

The configuration file `config/audit-logger.php` allows you to customize the behavior of the audit logger. Below are the key configuration options:

```
return [
    // Default audit driver
    'default' => env('AUDIT_DRIVER', 'mysql'),

    // Driver-specific configurations
    'drivers' => [
        'mysql' => [
            'connection' => env('AUDIT_MYSQL_CONNECTION', config('database.default')),
            'table_prefix' => env('AUDIT_TABLE_PREFIX', 'audit_'),
            'table_suffix' => env('AUDIT_TABLE_SUFFIX', '_logs'),
        ],
    ],

    // Queue processing configuration
    'queue' => [
        'enabled' => env('AUDIT_QUEUE_ENABLED', false),
        'connection' => env('AUDIT_QUEUE_CONNECTION', config('queue.default')),
        'queue_name' => env('AUDIT_QUEUE_NAME', 'audit'),
        'delay' => env('AUDIT_QUEUE_DELAY', 0),
    ],

    // Enable automatic migration for audit tables
    'auto_migration' => env('AUDIT_AUTO_MIGRATION', true),

    // Enhanced global field exclusions and configuration
    'fields' => [
        'exclude' => [
            'password',
            'remember_token',
            'api_token',
            'email_verified_at',
            'password_hash',
            'secret',
            'token',
            'private_key',
            'access_token',
            'refresh_token',
            'api_key',
            'secret_key',
            'stripe_id',
            'pm_type',
            'pm_last_four',
            'trial_ends_at',
        ],
        'include_timestamps' => true,
    ],

    // Enhanced causer identification settings
    'causer' => [
        'guard' => null, // null means use default guard
        'model' => null, // null means auto-detect
        'resolver' => null, // custom resolver class
    ],

    // Retention configuration for automatic cleanup
    'retention' => [
        'enabled' => env('AUDIT_RETENTION_ENABLED', false),
        'days' => env('AUDIT_RETENTION_DAYS', 365),
        'strategy' => env('AUDIT_RETENTION_STRATEGY', 'delete'), // 'delete', 'archive', 'anonymize'
        'batch_size' => env('AUDIT_RETENTION_BATCH_SIZE', 1000),
        'anonymize_after_days' => env('AUDIT_ANONYMIZE_DAYS', 180),
        'archive_connection' => env('AUDIT_ARCHIVE_CONNECTION', null),
        'run_cleanup_automatically' => env('AUDIT_AUTO_CLEANUP', false),
    ],

    // Registered entities for centralized configuration
    'entities' => [
        // Example entity configuration:
        // \App\Models\User::class => [
        //     'table' => 'users',
        //     'exclude' => ['password'],
        //     'include' => ['*'],
        //     'retention' => [
        //         'days' => 730,
        //         'strategy' => 'anonymize',
        //         'anonymize_after_days' => 365,
        //     ],
        // ],
    ],
];
```

### Environment Variables

[](#environment-variables)

You can use environment variables to configure the audit logger:

```
# Driver Configuration
AUDIT_DRIVER=mysql
AUDIT_MYSQL_CONNECTION=mysql
AUDIT_TABLE_PREFIX=audit_
AUDIT_TABLE_SUFFIX=_logs

# Queue Configuration
AUDIT_QUEUE_ENABLED=false
AUDIT_QUEUE_CONNECTION=redis
AUDIT_QUEUE_NAME=audit
AUDIT_QUEUE_DELAY=0

# Migration Configuration
AUDIT_AUTO_MIGRATION=true

# Retention Configuration
AUDIT_RETENTION_ENABLED=false
AUDIT_RETENTION_DAYS=365
AUDIT_RETENTION_STRATEGY=delete
AUDIT_RETENTION_BATCH_SIZE=1000
AUDIT_ANONYMIZE_DAYS=180
AUDIT_ARCHIVE_CONNECTION=null
AUDIT_AUTO_CLEANUP=false
```

### Database Schema

[](#database-schema)

The audit logger creates tables with the following structure for each audited model:

```
CREATE TABLE audit_{model_name}_logs (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    entity_id VARCHAR(255) NOT NULL,
    action VARCHAR(255) NOT NULL,
    old_values JSON NULL,
    new_values JSON NULL,
    causer_type VARCHAR(255) NULL,
    causer_id VARCHAR(255) NULL,
    metadata JSON NULL,
    source VARCHAR(255) NULL,
    created_at TIMESTAMP NOT NULL,
    anonymized_at TIMESTAMP NULL,

    INDEX idx_entity_id (entity_id),
    INDEX idx_causer (causer_type, causer_id),
    INDEX idx_created_at (created_at),
    INDEX idx_source (source),
    INDEX idx_action (action),
    INDEX idx_anonymized_at (anonymized_at)
);
```

The `source` field is automatically populated to track the origin of changes:

- Console commands: Command name (e.g., `app:send-emails`)
- HTTP requests: Controller action (e.g., `App\Http\Controllers\UserController@update`)
- Background jobs: Job class name
- Queue workers: Queue job processing context

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

To make a model auditable, simply add the `Auditable` trait to your Eloquent model. Ensure strict typing is enabled as per the engineering rules.

```
