PHP code example of mxnwire / laravel-audit-log

1. Go to this page and download the library: Download mxnwire/laravel-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/ */

    

mxnwire / laravel-audit-log example snippets


return [

    // A callable that decides whether the current request may view the logs.
    // It receives the authenticated user (or null) and must return a boolean.
    // Defaults to admins only; e.g. fn ($user) => $user?->can('AUDIT_LOGS_ALL') ?? false,
    'gate' => fn ($user) => $user?->role === 'admin',

    // A callable that resolves the actor's role label from a User model instance.
    // Receives the authenticated user (or null) and returns a string or null.
    'role_resolver' => fn ($user) => $user?->role ?? null,

    // Class supplying the viewer's filter dropdown options (log names, events,
    // subject types). Defaults to the DB-backed registry, which SELECT DISTINCTs
    // the live activity_log table. Point this at an AbstractAuditTypeRegistry
    // subclass to derive the options from a fixed vocabulary instead.
    // See "Custom audit type registry" below.
    'registry' => \Mxnwire\AuditLog\AuditTypeRegistry::class,

    // Properties recorded under each entry's `__request` context.
    // See "Configuring `__request`" below for the full reference.
    'request_context' => [
        'method', 'route', 'url', 'ip', 'user_agent', 'query',
        // 'body',   // off by default — request input can carry secrets
        'headers' => [
            'request_id'     => 'X-Request-Id',
            'correlation_id' => 'X-Correlation-Id',
        ],
    ],

    // Field names stripped from logged `query`/`body` input before storage.
    // Case-insensitive, recurses into nested arrays. See "Redacting secrets".
    'redact' => [
        'password', 'password_confirmation', 'token', 'secret', // …
    ],

    // URL prefix for the viewer routes.
    // Changing this also renames the named routes `audit-log.index` and `audit-log.data`.
    'route_prefix' => 'mxn/audit-logs',

    // Eloquent model used to populate the "User" filter dropdown.
    // The model must have `id` and `name` columns.
    // Set to null to hide the user filter entirely.
    'user_model' => 'App\\Models\\User',

    // Attributes of the causer (actor) exposed in the viewer's JSON response.
    // Only these keys survive serialization (the model's own `$hidden` still
    // applies first). Set to null to return the full causer model.
    'causer_attributes' => ['id', 'name', 'email'],

    // Blade layout the viewer page extends.
    // Override to wrap the viewer inside your own app shell.
    // The layout must @yield('content') and @yield('script').
    'layout' => 'audit-log::layouts.app',

];

audit_log('user.login');

use Mxnwire\AuditLog\Services\AuditLogService;

class AuthController extends Controller
{
    public function __construct(private AuditLogService $auditLog) {}

    public function login(Request $request)
    {
        // ... authenticate ...
        $this->auditLog->log('user.login');
    }
}

audit_log(
    string $action,                      // dotted verb, e.g. 'broadsheet.viewed'
    ?Model $subject = null,              // the record acted on
    ?AuditMetadata $metadata = null,  // structured diff / extra fields
    ?string $description = null          // optional human-readable label
): void

'request_context' => [
    // Enable built-ins by name:
    'method',
    'route',
    'url',
    'ip',
    'user_agent',
    'query',
    // 'body',   // off by default — enable to log request input

    // Add your own, resolved from anywhere (or override a built-in by name):
    'tenant_id'  => fn ($request) => $request->header('X-Tenant') ?? optional(tenant())->id,
    'user_agent' => fn ($request) => substr((string) $request->userAgent(), 0, 200),

    // Header-sourced values go under the `headers` group:
    'headers' => [
        'request_id'     => 'X-Request-Id',
        'correlation_id' => 'X-Correlation-Id',
    ],
],

'redact' => [
    'password',
    'password_confirmation',
    'token',
    'secret',
    // …
],

audit_log('order.placed', $order, AuditMetadata::make([
    'request_id' => $myTraceId,
]));

use Mxnwire\AuditLog\Audit\Metadata\AuditMetadata;

audit_log(
    'user.login',
    subject: $user,
    metadata: AuditMetadata::make(['via' => 'password'])
);

use Mxnwire\AuditLog\Audit\Metadata\AuditMetadata;
use Mxnwire\AuditLog\Audit\Metadata\Change;

audit_log(
    'subscription.updated',
    subject: $subscription,
    metadata: AuditMetadata::make([
        'level' => Change::make($old->level, $new->level),
    ])
);

$metadata = AuditMetadata::diff(
    $record->getOriginal(),  // before
    $record->getAttributes() // after
);

audit_log('post.updated', subject: $record, metadata: $metadata);

AuditMetadata::diff($before, $after, keys: ['title', 'status', 'published_at']);

AuditMetadata::diff($before, $after)
    ->with('trigger', 'bulk-import')
    ->with('row_count', 500);

'layout' => 'layouts.app',

'route_prefix' => 'admin/audit-logs',

'role_resolver' => fn ($user) => $user->roles->first()?->name,

use Mxnwire\AuditLog\AbstractAuditTypeRegistry;

class AuditType extends AbstractAuditTypeRegistry
{
    const RANK_UPDATED      = 'rank.updated';
    const BROADSHEET_VIEWED = 'broadsheet.viewed';

    protected const SUBJECT_MODELS = [
        'rank' => \App\Models\Rank::class,
    ];
}

'registry' => \App\Audit\AuditType::class,

use Mxnwire\AuditLog\Contracts\AuditTypeRegistryContract;

$this->app->bind(AuditTypeRegistryContract::class, MyCustomRegistry::class);
bash
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="audit-log"
bash
./vendor/bin/phpunit tests/Unit/AuditMetadataTest.php
./vendor/bin/phpunit tests/Unit/ChangeTest.php
./vendor/bin/phpunit tests/Feature/AuditLogServiceTest.php