PHP code example of grazulex / laravel-snapshot

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

    

grazulex / laravel-snapshot example snippets


use Grazulex\LaravelSnapshot\Traits\HasSnapshots;

class User extends Model
{
    use HasSnapshots;
    
    // Optionally specify which attributes to track
    protected $snapshotable = ['name', 'email', 'status'];
    
    // Exclude sensitive attributes
    protected $snapshotExclude = ['password', 'remember_token'];
}

// Automatic snapshots on model events
class User extends Model
{
    use HasSnapshots;
    
    protected $snapshotEvents = ['created', 'updated', 'deleted'];
    
    // Custom snapshot triggers
    protected $snapshotTriggers = [
        'status_changed' => function ($model) {
            return $model->isDirty('status');
        }
    ];
}

$user = User::find(1);

// Create manual snapshot
$snapshot = $user->createSnapshot('Before important update');

// Update the model
$user->update(['status' => 'active', 'email' => '[email protected]']);

// Get all snapshots
$snapshots = $user->snapshots()->orderBy('created_at', 'desc')->get();

// Get specific snapshot
$latestSnapshot = $user->latestSnapshot();
$firstSnapshot = $user->firstSnapshot();

// Restore to latest snapshot
$user->restoreFromLatestSnapshot();

// Restore to specific snapshot
$user->restoreFromSnapshot($snapshot);

// Restore to specific date
$user->restoreToDate(now()->subDays(7));

// Preview restoration (without saving)
$previewData = $user->previewRestore($snapshot);

// Basic snapshot
$user->createSnapshot();

// Snapshot with description
$user->createSnapshot('User activated premium account');

// Snapshot with metadata
$user->createSnapshot('Status change', [
    'triggered_by' => auth()->id(),
    'reason' => 'Admin approval',
]);

// Conditional snapshots
$user->createSnapshotIf($user->isDirty('email'), 'Email updated');

// Simple restoration
$user->restoreFromSnapshot($snapshot);

// Restoration with validation
$user->restoreFromSnapshot($snapshot, ['validate' => true]);

// Selective restoration (only specific attributes)
$user->restoreFromSnapshot($snapshot, ['only' => ['name', 'status']]);

// Restore to specific date
$user->restoreToDate(now()->subDays(7));

use Grazulex\LaravelSnapshot\Analysis\Differ;

$user = User::find(1);

// Compare current state with snapshot
$diff = $user->diffWithSnapshot($snapshot);

foreach ($diff->getChanges() as $attribute => $change) {
    echo "Attribute: {$attribute}\n";
    echo "Old value: {$change['old']}\n";
    echo "New value: {$change['new']}\n";
    echo "Change type: {$change['type']}\n"; // added, modified, removed
}

// Compare two snapshots
$diff = Differ::compare($snapshot1, $snapshot2);

// Visual diff output
echo $diff->toHtml(); // HTML formatted diff
echo $diff->toMarkdown(); // Markdown formatted diff

// Diff statistics
$stats = $diff->getStats();
echo "Total changes: {$stats['total']}\n";
echo "Added: {$stats['added']}\n";
echo "Modified: {$stats['modified']}\n";
echo "Removed: {$stats['removed']}\n";

// config/snapshot.php
return [
    'storage' => [
        'driver' => 'database', // database, file, s3
        'table' => 'model_snapshots',
        'compress' => true,
    ],
    
    'automatic' => [
        'enabled' => true,
        'events' => ['created', 'updated'],
        'throttle' => '1 minute', // Prevent duplicate snapshots
    ],
    
    'retention' => [
        'enabled' => true,
        'keep_snapshots' => 100,
        'keep_for_days' => 365,
    ],
    
    'features' => [
        'track_relationships' => true,
        'track_metadata' => true,
        'validate_integrity' => true,
    ],
];

use Grazulex\LaravelSnapshot\Facades\Snapshot;

// Batch snapshot creation
Snapshot::batch(function () {
    $users = User::where('created_at', '>=', now()->subDays(7))->get();
    
    foreach ($users as $user) {
        $user->createSnapshot('Weekly backup');
    }
});

// Snapshot with complex metadata
$order = Order::find(1);
$order->createSnapshot('Order processed', [
    'processor' => auth()->user()->name,
    'location' => request()->header('X-Location'),
    'version' => config('app.version'),
    'environment' => app()->environment(),
]);

// Conditional restoration
$user = User::find(1);
$snapshot = $user->snapshots()->where('description', 'Before migration')->first();

if ($snapshot && $user->shouldRestore($snapshot)) {
    $user->restoreFromSnapshot($snapshot);
}

// Custom audit trail using snapshots
class AuditTrail
{
    public static function track($model, $action)
    {
        $model->createSnapshot("Audit: {$action}", [
            'audit_action' => $action,
            'user_id' => auth()->id(),
            'timestamp' => now(),
            'session_id' => session()->getId(),
        ]);
    }
    
    public static function getAuditLog($model)
    {
        return $model->snapshots()
            ->whereJsonContains('metadata->audit_action', '!=', null)
            ->orderBy('created_at', 'desc')
            ->get();
    }
}

// Usage
AuditTrail::track($user, 'login');
AuditTrail::track($user, 'profile_update');
$auditLog = AuditTrail::getAuditLog($user);

// Data recovery service
class DataRecoveryService
{
    public function recoverToDate($model, $date)
    {
        $snapshot = $model->snapshots()
            ->where('created_at', '<=', $date)
            ->orderBy('created_at', 'desc')
            ->first();
            
        if ($snapshot) {
            return $model->restoreFromSnapshot($snapshot);
        }
        
        throw new Exception('No snapshot found for the specified date');
    }
    
    public function previewRecovery($model, $snapshot)
    {
        $current = $model->toArray();
        $restored = $snapshot->data;
        
        return [
            'current' => $current,
            'restored' => $restored,
            'changes' => array_diff_assoc($restored, $current),
        ];
    }
}

use Grazulex\LaravelSnapshot\Testing\SnapshotTester;

public function test_model_snapshot_creation()
{
    $user = User::factory()->create();
    
    SnapshotTester::make($user)
        ->createSnapshot('Test snapshot')
        ->assertSnapshotExists()
        ->assertSnapshotCount(1)
        ->assertSnapshotContains(['name', 'email']);
}

public function test_model_restoration()
{
    $user = User::factory()->create(['status' => 'inactive']);
    $snapshot = $user->createSnapshot();
    
    $user->update(['status' => 'active']);
    
    SnapshotTester::make($user)
        ->restoreFromSnapshot($snapshot)
        ->assertRestoredSuccessfully()
        ->assertAttribute('status', 'inactive');
}
bash
php artisan vendor:publish --tag=snapshot-config
bash
php artisan vendor:publish --tag=snapshot-migrations
php artisan migrate