PHP code example of faustvik / yii2-audit-log

1. Go to this page and download the library: Download faustvik/yii2-audit-log library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

faustvik / yii2-audit-log example snippets


use FaustVik\AuditLog\Yii2\Integration\AuditLogBehavior;

class User extends ActiveRecord
{
    public function behaviors(): array
    {
        return [
            'auditLog' => [
                'class' => AuditLogBehavior::class,
                'excludeAttributes' => ['hash_password', 'auth_key'],
            ],
        ];
    }
}

<?= \FaustVik\AuditLog\Yii2\Integration\AuditLogFilterWidget::widget([
    'model'    => $user,
    'pageSize' => 20,
    'title'    => 'Change History',
]) 

// In bootstrap.php
Yii::$app->on(
    \FaustVik\AuditLog\Core\Events\BeforeLogEvent::class,
    function (\FaustVik\AuditLog\Core\Events\BeforeLogEvent $event) {
        // Cancel logging for specific operations
        if ($event->entityClass === User::class && $event->operation->value === 'DELETE') {
            $event->stopPropagation();
        }
    }
);

/** @var \FaustVik\AuditLog\Core\Contracts\AuditLoggerInterface $logger */

$logger->logBatch([
    [
        'entityClass' => User::class,
        'entityId'    => 1,
        'operation'   => \FaustVik\AuditLog\Core\Enums\Operation::Update,
        'changedAttributes' => [
            'status' => ['old' => 'active', 'new' => 'banned'],
        ],
        'customData' => ['reason' => 'policy violation'],
    ],
    [
        'entityClass' => UserProfile::class,
        'entityId'    => 1,
        'operation'   => \FaustVik\AuditLog\Core\Enums\Operation::Update,
    ],
]);

Yii::$app->on(
    \FaustVik\AuditLog\Core\Events\BeforeLogBatchEvent::class,
    function (\FaustVik\AuditLog\Core\Events\BeforeLogBatchEvent $event) {
        // Stop the entire batch
        $event->stopPropagation();

        // Or filter items — remove sensitive entities
        $event->items = array_values(array_filter(
            $event->items,
            fn ($item) => $item['entityClass'] !== SensitiveModel::class,
        ));
    }
);

use FaustVik\AuditLog\Core\Query\AuditLogQuery;
use FaustVik\AuditLog\Core\Contracts\AuditStorageInterface;

$storage = Yii::createObject(AuditStorageInterface::class);

// All changes for a specific User record
$logs = (new AuditLogQuery($storage))
    ->forEntityClass(User::class)
    ->forEntityId($userId)
    ->operation(\FaustVik\AuditLog\Core\Enums\Operation::Update)
    ->dateRange('2025-01-01', '2025-12-31')
    ->limit(50)
    ->all();

// All changes across all User records today (no specific ID