PHP code example of iamfarhad / laravel-audit-log

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

    

iamfarhad / laravel-audit-log example snippets


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'),
        ],
    ],

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

    // Global field exclusions
    'fields' => [
        'exclude' => [
            'password',
            'remember_token',
            'api_token',
        ],
        '



declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use iamfarhad\LaravelAuditLog\Traits\Auditable;

final class Order extends Model
{
    use Auditable;

    protected $fillable = ['customer_id', 'total', 'status'];
}



declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use iamfarhad\LaravelAuditLog\Traits\Auditable;

final class User extends Model
{
    use Auditable;

    protected array $auditExclude = [
        'password',
        'remember_token',
    ];
}



declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use iamfarhad\LaravelAuditLog\Traits\Auditable;

final class Invoice extends Model
{
    use Auditable;

    protected array $auditInclude = [
        'amount',
        'status',
        'due_date',
    ];
}



declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use iamfarhad\LaravelAuditLog\Traits\Auditable;

final class Transaction extends Model
{
    use Auditable;

    public function getAuditMetadata(): array
    {
        return [
            'ip_address' => request()->ip() ?? 'unknown',
            'user_agent' => request()->userAgent() ?? 'unknown',
            'request_id' => request()->header('X-Request-Id', 'n/a'),
        ];
    }
}

$user = User::find(1);
$user->disableAuditing();
$user->update(['email' => '[email protected]']); // This change won't be logged
$user->enableAuditing();



declare(strict_types=1);

use Illuminate\Support\Facades\Event;
use iamfarhad\LaravelAuditLog\Events\ModelAudited;

$order = Order::find(1);
Event::dispatch(new ModelAudited(
    model: $order,
    action: 'status_changed',
    oldValues: ['status' => 'pending'],
    newValues: ['status' => 'shipped']
));



declare(strict_types=1);

use App\Models\Order;

$order = Order::find(1);
$order->audit()
    ->custom('status_transition')
    ->from(['status' => 'pending'])
    ->to(['status' => 'shipped'])
    ->withMetadata(['ip' => request()->ip(), 'user_agent' => request()->userAgent()])
    ->log();



declare(strict_types=1);

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use iamfarhad\LaravelAuditLog\Contracts\AuditDriverInterface;
use App\Audit\CustomAuditDriver;

final class AuditServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(AuditDriverInterface::class, CustomAuditDriver::class);
    }
}

$user = User::find(1);

// Retrieve all audit logs
$allLogs = $user->auditLogs()->get();

// Filter by specific action
$updateLogs = $user->auditLogs()->where('action', 'updated')->get();

// Get the most recent logs
$recentLogs = $user->auditLogs()->orderBy('created_at', 'desc')->take(5)->get();



declare(strict_types=1);

use iamfarhad\LaravelAuditLog\Models\EloquentAuditLog;

// Get logs for a specific entity type and ID
$logs = EloquentAuditLog::forEntity(User::class)
    ->where('entity_id', 1)
    ->where('action', 'updated')
    ->where('created_at', '>=', now()->subDays(7))
    ->orderBy('created_at', 'desc')
    ->get();

// Use scope to filter by action type
$createdLogs = EloquentAuditLog::forEntity(User::class)
    ->action('created')
    ->where('entity_id', 1)
    ->get();

// Use scope to filter by date range
$lastMonthLogs = EloquentAuditLog::forEntity(User::class)
    ->dateBetween(now()->subDays(30), now())
    ->where('entity_id', 1)
    ->orderBy('created_at', 'desc')
    ->get();

// Use scope to filter by causer (user who performed the action)
$adminLogs = EloquentAuditLog::forEntity(User::class)
    ->causer(1) // Assuming causer_id 1 is the admin
    ->where('entity_id', 1)
    ->get();

// Combine multiple scopes for precise filtering
$filteredLogs = EloquentAuditLog::forEntity(User::class)
    ->action('updated')
    ->causer(1)
    ->dateBetween(now()->subDays(7), now())
    ->where('entity_id', 1)
    ->orderBy('created_at', 'desc')
    ->take(10)
    ->get();

  'batch' => [
      'enabled' => true,
      'size' => 100,
  ],
  
bash
php artisan vendor:publish --tag=audit-logger-config