PHP code example of ernestoch / user-auditable-for-laravel

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

    

ernestoch / user-auditable-for-laravel example snippets


// Basic usage with default values
Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->fullAuditable(); // Adds timestamps, soft deletes, and user auditing
});

// Custom user table and UUID key type
Schema::create('products', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('name');
    $table->fullAuditable('admins', 'uuid');
});

// Only user auditing columns (no timestamps or soft deletes)
Schema::create('settings', function (Blueprint $table) {
    $table->string('key')->primary();
    $table->text('value');
    $table->userAuditable('users', 'ulid');
});


// Both columns: released_at (timestamp) + released_by (FK to users)
Schema::table('products', function (Blueprint $table) {
    $table->eventAuditable('released');
});

// Timestamp only: approved_at
Schema::table('orders', function (Blueprint $table) {
    $table->eventAuditable('approved', 'at');
});

// FK only: archived_by
Schema::table('posts', function (Blueprint $table) {
    $table->eventAuditable('archived', 'by');
});

// Reverse fullAuditable()
Schema::table('posts', function (Blueprint $table) {
    $table->dropFullAuditable(); // Drops timestamps, soft deletes, and audit columns
});

// Reverse userAuditable()
Schema::table('settings', function (Blueprint $table) {
    $table->dropUserAuditable(); // Drops audit columns only
});

// Reverse uuidColumn()
Schema::table('products', function (Blueprint $table) {
    $table->dropUuidColumn();
    // or with custom column name:
    // $table->dropUuidColumn('product_uuid');
});

// Reverse ulidColumn()
Schema::table('orders', function (Blueprint $table) {
    $table->dropUlidColumn();
    // or with custom column name:
    // $table->dropUlidColumn('order_ulid');
});

// Reverse statusColumn()
Schema::table('users', function (Blueprint $table) {
    $table->dropStatusColumn();
    // or with custom column name:
    // $table->dropStatusColumn('user_status');
});

// Reverse eventAuditable()
Schema::table('products', function (Blueprint $table) {
    $table->dropEventAuditable('released');     // Both columns
    $table->dropEventAuditable('released', 'by'); // Only released_by
    $table->dropEventAuditable('released', 'at'); // Only approved_at
});



namespace App\Models;

use ErnestoCh\UserAuditable\Traits\UserAuditable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes, UserAuditable;

    protected $fillable = [
        'title',
        'content',
        'created_by',
        'updated_by',
        'deleted_by'
    ];
}



namespace App\Models;

use ErnestoCh\UserAuditable\Traits\EventAuditable;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use EventAuditable;

    protected $fillable = [
        'name',
        'released_by',
        'released_at',
        'approved_by',
        'approved_at'
    ];
}

$post = Post::first();

// Get the user who created the post
$creator = $post->creator;

// Get the user who updated the post
$updater = $post->updater;

// Get the user who deleted the post (if using soft deletes)
$deleter = $post->deleter;

$product = Product::first();

// Get user who released the product
$releasedBy = $product->releasedBy(); // BelongsTo User

// Get user who approved the product
$approvedBy = $product->approvedBy(); // BelongsTo User

// Works for any event defined via eventAuditable() macro
$archivedBy = $product->archivedBy();

// Get all posts created by user with ID 1
$posts = Post::createdBy(1)->get();

// Get all posts updated by user with ID 2
$posts = Post::updatedBy(2)->get();

// Get all posts deleted by user with ID 3
$posts = Post::deletedBy(3)->get();

// Get products released by user with ID 5
$released = Product::releasedBy(5)->get();

// Get products approved by user with ID 10
$approved = Product::approvedBy(10)->get();

// Works for any event defined via eventAuditable() macro
$archived = Product::archivedBy(8)->get();

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('audit_logs', function (Blueprint $table) {
            $table->auditLogTable();
        });
    }

    public function down(): void
    {
        Schema::table('audit_logs', function (Blueprint $table) {
            $table->dropAuditLogTable();
        });
    }
};



namespace App\Models;

use ErnestoCh\UserAuditable\Traits\ChangeAuditable;
use ErnestoCh\UserAuditable\Traits\EventAuditable;
use ErnestoCh\UserAuditable\Traits\UserAuditable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use ChangeAuditable, EventAuditable, SoftDeletes, UserAuditable;

    protected $fillable = ['title', 'content', 'status'];

    // Fields to never log (denylist)
    protected array $auditExclude = ['internal_notes'];

    // Or log only specific fields (allowlist — overrides auditExclude)
    // protected array $auditInclude = ['title', 'status'];
}

$post = Post::find(1);

// All audit entries (MorphMany)
$logs = $post->auditLogs()->get();

// Most recent entry
$latest = $post->lastAuditLog();

// Filter by event
$updates = $post->auditLogs()->where('event', 'updated')->get();

// Each AuditLog entry has:
// $log->event        // 'created' | 'updated' | 'deleted' | 'restored' | 'reverted'
// $log->old_values   // array|null
// $log->new_values   // array|null
// $log->user_id
// $log->user_type
// $log->ip_address
// $log->user_agent
// $log->created_at

$post = Post::find(1);

// Get an older 'updated' log
$log = $post->auditLogs()->where('event', 'updated')->latest('id')->first();

// Restore the model to that state
$post->revertTo($log); // returns true on success

$logs = $post->auditLogs()->where('event', 'updated')->oldest('id')->get();

$diff = $post->diffBetween($logs->first(), $logs->last());
// [
//   'title' => ['from' => 'Old Title', 'to' => 'New Title'],
//   'status' => ['from' => 'draft', 'to' => 'published'],
// ]

use ErnestoCh\UserAuditable\Models\AuditLog;

// Delete all entries older than 90 days
$deleted = AuditLog::pruneOlderThan(90);

// config/user-auditable.php
'change_tracking' => [
    'enabled'            => true,
    'table'              => 'audit_logs',
    'retain_days'        => null,    // null = keep forever
    'log_created'        => true,
    'log_updated'        => true,
    'log_deleted'        => true,
    'log_restored'       => true,
    'user_resolver'      => null,    // callable($model): mixed
    'user_type_resolver' => null,    // callable($model): string|null
],
bash
php artisan vendor:publish --tag=user-auditable-config