PHP code example of dvarilek / laravel-snap

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

    

dvarilek / laravel-snap example snippets


use Dvarilek\LaravelSnap\Models\Concerns\Snapshotable;
use Dvarilek\LaravelSnap\ValueObjects\SnapshotDefinition;

class MyModel extends Model
{
    use Snapshotable;        
    
    public static function getSnapshotDefinition(): SnapshotDefinition
    {
        return SnapshotDefinition::make()
            ->captureAll();
    }
    
    // ...
}

$firstSnapshot = $model->takeSnapshot();

// Access captured Snapshot attribute directly
$name = $firstSnapshot->name;
$email = $firstSnapshot->email;

$model->update([
    'email' => 'different email'
])

$secondSnapshot = $model->takeSnapshot();

$firstSnapshot->email === $secondSnapshot->email; // false
$firstSnapshot->email === $model->email; // false
$secondSnapshot->email === $model->email; // true

SnapshotDefinition::make()
    ->captureAll();

SnapshotDefinition::make()
    ->capture([
        'title',
        'description',
        'status'
    ]);

SnapshotDefinition::make()
    ->captureHiddenAttributes()

SnapshotDefinition::make()
    ->captureAll()
    ->exclude([
        'password', 
        'remember_token'
    ]);

SnapshotDefinition::make()
    ->captureCasts(false);

SnapshotDefinition::make()
    ->captureAll()
    ->excludeTimestamps();

use Dvarilek\LaravelSnap\ValueObjects\{SnapshotDefinition, RelationDefinition}

SnapshotDefinition::make()
    ->captureRelations([
        RelationDefinition::from('branch')    
            ->capture([
                'name', 
                'address' 
            ]),     
        RelationDefinition::from('supervisor')    
            ->capture([
                'name' 
            ]),
        // ... Multiple RelationDefinitions can be specified     
    ]);

// Captured attributes in Snapshot
// branch_name
// branch_address
// supervisor_name

use Dvarilek\LaravelSnap\ValueObjects\{SnapshotDefinition, RelationDefinition}

SnapshotDefinition::make()
    ->captureRelations([
        RelationDefinition::from('custodian')
            ->capture([
                'name',
                'email'
            ])
            ->captureRelations([
                RelationDefinition::from('department')
                    ->capture([
                        'name', 
                    ]),
                // ...
            ]),
            // ...
    ]);
    
// Captured attributes in snapshot
// custodian_name
// custodian_email
// custodian_department_name


$snapshot = $model->takeSnapshot();


// Store the currently authenticated user that created the Snapshot 
$snapshot = $model->takeSnapshot(extraAttributes: [
    'created_by' => auth()->id()
]);

  
// Get the most recent snapshot
$latest = $model->latestSnapshot;

// Get the first snapshot ever taken
$oldest = $model->oldestSnapshot;


$snapshot = $model->takeSnapshot();

// Access captured attributes directly
$name = $snapshot->name;
$email = $snapshot->email;
$supervisorName = $snapshot->supervisor_name;

// Mass assignment
$snapshot->update([
    'name' => 'New Name',
    'email' => '[email protected]'
]);

// Individual property updates
$snapshot->age = 25;
$snapshot->save();

use Dvarilek\LaravelSnap\Models\Snapshot;

// For captured attribute by the name 'custodian_name'
Snapshot::query()->where('storage->custodian_name->value', $custodianName);

// Get the most recent snapshot
$snapshot = $model->latestSnapshot;

// Revert the model to that snapshot
$model = $model->revertTo($snapshot);

$model = $model->latestSnapshot->sync();

// Revert the model and attributes of related models from the Snapshot (true by default)
$model = $model->revertTo($snapshot, shouldRestoreRelatedAttributes: true);

// Rewind the model by one step backwards (default)
$model->rewind();

// Rewind the model by three steps backwards
$model->rewind(3);

// Move forward by one step (default)
$model->forward();

// Move forward by two steps
$model->forward(2);

// Default values: 
$model->rewind(shouldDefaultToNearest: false, shouldRestoreRelatedAttributes: true);

$model->forward(shouldDefaultToNearest: false, shouldRestoreRelatedAttributes: true);

use Dvarilek\LaravelSnap\Models\Concerns\Snapshotable;
use Dvarilek\LaravelSnap\ValueObjects\SnapshotDefinition;

class MyModel extends Model
{
    use Snapshotable;        
    
    // ...
    
    public static function booted(): void
    {
        
        // ...
    
        static::snapshotting(function () {
            // Executes before snapshot creation
            // Return false to prevent the snapshot from being created
        });
        
        static::snapshot(function () {
            // Executes after successful snapshot creation        
        });
        
        static::reverting(function () {
            // Executes before model state is reverted
            // Return false to cancel the reverting operation
        });
        
        static::reverted(function () {
            // Executes after model state has been successfully reverted
        });
    }
}

use Dvarilek\LaravelSnap\DTO\{AttributeTransferObject, RelatedAttributeTransferObject}
use Illuminate\Database\Eloquent\Casts\{AsStringable, AsCollection};

$snapshot->update([
    // Base model attribute with custom casting
    'name' => new AttributeTransferObject(
        attribute: 'name',
        value: 'some different value',
        cast: AsStringable::class
    ),
    
    // Related model attribute with collection casting
    'contract_files' => new RelatedAttributeTransferObject(
        attribute: 'files',
        value: ['path/to/file1'. 'path/to/file2'],
        cast: AsCollection::class,
        relationPath:  => ['department']
    )
]);

// Create a Snapshot with invoices as an extra attribute
$snapshot = $model->takeSnapshot(extraAttributes: [
    'invoices' => new AttributeTransferObject(
        attribute: 'invoices',
        value: ['path/to/file1'. 'path/to/file2'],
        cast: 'array'
    ),
]);
bash
php artisan laravel-snap:install
bash
php artisan vendor:publish --tag=snap-config
bash
php artisan laravel-snap:make-versionable "App\Models\YourModel"