Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Db Snapshots Laravel Package

spatie/laravel-db-snapshots

Artisan commands to quickly create, load, list, and clean up database snapshots in Laravel. Dump your DB, restore any snapshot (or the latest), and keep only recent dumps. Supports MySQL, PostgreSQL, and SQLite.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require spatie/laravel-db-snapshots
    
  2. Configure storage disk in config/filesystems.php:
    'disks' => [
        'snapshots' => [
            'driver' => 'local',
            'root' => database_path('snapshots'),
        ],
    ],
    
  3. Publish config (optional):
    php artisan vendor:publish --provider="Spatie\DbSnapshots\DbSnapshotsServiceProvider"
    

First Use Case: Creating a Baseline Snapshot

# Create a snapshot with default timestamp naming
php artisan snapshot:create

# Or explicitly name it
php artisan snapshot:create production-baseline

Quick Verification

# List all snapshots
php artisan snapshot:list

Implementation Patterns

Workflow: Feature Development with Snapshots

  1. Create a baseline snapshot before starting a feature:
    php artisan snapshot:create feature-x-baseline
    
  2. Restore baseline after testing:
    php artisan snapshot:load feature-x-baseline
    
  3. Incremental snapshots for changes:
    php artisan snapshot:create feature-x-v2
    

Selective Table Snapshots

# Include only specific tables
php artisan snapshot:create --table=users,posts

# Exclude tables
php artisan snapshot:create --exclude=logs,migrations

Multi-Environment Snapshots

# Use different connections
php artisan snapshot:create --connection=staging

# Load into a specific connection
php artisan snapshot:load staging-backup --connection=production

Automated Cleanup

# Keep only the last 5 snapshots
php artisan snapshot:cleanup --keep=5

Integration with CI/CD

# Example GitHub Actions workflow
jobs:
  test:
    steps:
      - name: Load baseline snapshot
        run: php artisan snapshot:load baseline
      - name: Run tests
        run: php artisan test
      - name: Create snapshot after tests
        run: php artisan snapshot:create test-run-$(date +%s)

Event-Driven Extensions

// Listen for snapshot creation
DbSnapshots::creating(function (CreatingSnapshot $event) {
    Log::info('Creating snapshot: '.$event->name);
});

// Post-load actions
DbSnapshots::loaded(function (LoadedSnapshot $event) {
    Cache::clear();
});

Gotchas and Tips

Common Pitfalls

  1. Connection Mismatch:

    • Ensure the target connection in snapshot:load matches the source connection of the snapshot.
    • Fix: Use --connection flag or verify config/database.php.
  2. Large File Handling:

    • Loading large snapshots may hit memory limits.
    • Fix: Use --stream flag:
      php artisan snapshot:load big-snapshot --stream
      
  3. Table Exclusions:

    • --exclude is ignored if --table is specified.
    • Workaround: Create two separate snapshots or use config:
      'tables' => ['users', 'posts'], // Only these tables
      'exclude' => ['logs'],         // Exclude from above
      
  4. Compression Issues:

    • Gzipped snapshots may fail on some systems.
    • Fix: Disable compression in config or use --compress=false.
  5. Foreign Key Constraints:

    • Loading snapshots may fail if constraints exist.
    • Fix: Temporarily disable constraints:
      php artisan snapshot:load --drop-tables=0 --stream
      SET FOREIGN_KEY_CHECKS=0; -- Add this to your snapshot file
      

Debugging Tips

  1. Inspect Snapshot Contents:

    # View raw SQL (Linux/macOS)
    zcat database/snapshots/my-snapshot.sql.gz | less
    
  2. Check Disk Space:

    • Ensure the snapshots disk has sufficient space (default: database_path('snapshots')).
  3. Event Debugging:

    // Log event payloads
    DbSnapshots::creating(fn($e) => Log::debug($e->payload));
    

Advanced Configurations

  1. Custom Temporary Directory:

    'temporary_directory_path' => sys_get_temp_dir().'/laravel-snapshots',
    
  2. Database-Specific Options:

    // config/database.php
    'connections' => [
        'pgsql' => [
            'dump' => [
                'addExtraOption' => '--no-owner --no-privileges',
            ],
        ],
    ],
    
  3. Environment-Specific Snapshots:

    // config/db-snapshots.php
    'disk' => env('DB_SNAPSHOT_DISK', 'snapshots'),
    

Extension Points

  1. Custom Snapshot Storage:

    • Implement Spatie\DbSnapshots\Contracts\SnapshotStorage to use S3, etc.
  2. Pre/Post Actions:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        DbSnapshots::creating(fn($e) => $this->preSnapshotActions());
        DbSnapshots::loaded(fn($e) => $this->postLoadActions());
    }
    
  3. Snapshot Naming Logic:

    • Override Spatie\DbSnapshots\SnapshotNameGenerator for custom naming.

Performance Considerations

  • Compression: Enable for large databases ('compress' => true).
  • Streaming: Always use --stream for snapshots >100MB.
  • Exclusions: Exclude migrations, failed_jobs, and large logs tables.

Security Notes

  • Permissions: Ensure the snapshots directory is writable by the web server.
  • Sensitive Data: Never store snapshots containing PII in version control.
  • Cleanup: Automate cleanup in CI/CD to avoid disk bloat.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport