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 Backup Laravel Package

spatie/laravel-backup

Spatie Laravel Backup creates zip backups of your app files and database, storing them on any Laravel filesystem (even multiple). Includes health monitoring, notifications, and automatic cleanup of old backups. Run with php artisan backup:run.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-backup
    php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"
    

    This publishes the default config (config/backup.php) and migrations (if using database monitoring).

  2. First Backup:

    php artisan backup:run
    

    By default, this backs up:

    • All files in storage/ and bootstrap/cache/
    • The primary database (configured in .env)
  3. Where to Look First:

    • Config: config/backup.php (define sources, destinations, schedules, and cleanup rules).
    • Artisan Commands:
      • backup:run – Create a backup.
      • backup:monitor – Check backup health.
      • backup:clean – Remove old backups.
    • Destinations: Configure in destinations array (e.g., s3, ftp, local, or custom filesystems).
  4. First Use Case: Schedule a daily backup to S3 and local storage:

    // config/backup.php
    'schedules' => [
        \Spatie\Backup\Tasks\ScheduleTask::class => [
            \Spatie\Backup\Tasks\Backup\CreateBackup::class,
            \Spatie\Backup\Tasks\Backup\Notify::class,
        ],
    ],
    

    Then add to app/Console/Kernel.php:

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('backup:run')->daily();
    }
    

Implementation Patterns

Core Workflows

  1. Defining Backup Sources:

    'sources' => [
        \Spatie\Backup\Tasks\Backup\Sources\Source::local()
            ->addFiles('/path/to/custom/directory')
            ->addDatabase(MySqlDatabase::create())
            ->addDatabase(PostgresDatabase::create())
            ->addDatabase(MongoDatabase::create()),
    ],
    
    • Use Source::local() for file backups.
    • Chain methods like addFiles(), addDatabase(), or exclude() for granular control.
  2. Multi-Destination Backups:

    'destinations' => [
        'local' => [
            'driver' => 'local',
            'path' => storage_path('backups'),
        ],
        's3' => [
            'driver' => 's3',
            'bucket' => 'my-backup-bucket',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => 'us-east-1',
            'path' => 'laravel-backups',
        ],
    ],
    
    • Backups are written to all configured destinations in parallel.
    • Use BackupDestination::create() for custom logic (e.g., encryption).
  3. Monitoring Backup Health:

    php artisan backup:monitor
    
    • Checks for:
      • Corrupted backups (via checksums).
      • Missing files/databases.
      • Destination connectivity.
    • Logs issues to storage/logs/laravel-backup.log by default.
  4. Notifications:

    'notifications' => [
        'notifiable' => \App\Notifications\BackupFailed::class,
        'channel' => 'mail', // or 'slack', 'database', etc.
    ],
    
    • Extend Spatie\Backup\Notifications\BackupNotification for custom logic.
    • Use events (BackupWasSuccessful, BackupHasFailed) to trigger notifications.
  5. Cleanup Automation:

    php artisan backup:clean
    
    • Configure retention in config/backup.php under cleanup.default_strategy.
    • Example: Keep daily backups for 16 days, weekly for 8 weeks, etc.
    • Custom strategies via CleanupStrategy interface.

Integration Tips

  • Database-Specific Backups:

    $database = MySqlDatabase::create()
        ->setUssername(env('DB_USERNAME'))
        ->setPassword(env('DB_PASSWORD'))
        ->setHost(env('DB_HOST'))
        ->setName(env('DB_DATABASE'))
        ->setSocket('/path/to/mysql.sock'); // For socket-based connections
    
    • Supports MySQL, PostgreSQL, SQLite, and MongoDB.
  • Excluding Files:

    Source::local()->exclude(['storage/logs/*', 'node_modules/*']);
    
  • Encryption:

    use Spatie\Backup\Tasks\Backup\EncryptBackup;
    
    'tasks' => [
        EncryptBackup::class,
    ],
    
    • Uses OpenSSL; configure key in config/backup.php.
  • Testing Backups:

    php artisan backup:run --test
    
    • Runs a dry backup (no files written) to validate configuration.
  • Custom Destinations:

    BackupDestination::create('custom')
        ->type(\Spatie\Backup\BackupDestination\BackupDestinationType::FTP)
        ->connection('ftp_connection_name')
        ->path('backups/laravel');
    

Gotchas and Tips

Pitfalls

  1. Disk Space:

    • Ensure destinations have at least the total size of all sources + overhead.
    • Monitor disk space with df -h (Linux) or Get-PSDrive (Windows).
  2. Large Databases:

    • MySQL/PostgreSQL dumps can bloat backups. Use --single-transaction for MySQL to avoid locks:
      MySqlDatabase::create()->setDumpOptions(['--single-transaction']);
      
    • For MongoDB, use --gzip to compress dumps:
      MongoDatabase::create()->setDumpOptions(['--gzip']);
      
  3. Permission Issues:

    • Ensure the Laravel user has read access to all source directories.
    • For S3/FTP, verify IAM roles or credentials have write permissions.
  4. Windows Limitations:

    • The package does not support Windows due to ZIP module quirks. Use Linux or WSL.
  5. Time Zones in Cleanup:

    • Cleanup rules use the server’s time zone. Adjust config/app.php if needed.
  6. Monitoring False Positives:

    • Checksum mismatches may occur if files change during backup. Use backup:monitor --ignore-checksums to bypass temporarily.
  7. Database Connection Drops:

    • Long-running dumps may timeout. Increase max_execution_time in php.ini or use chunked backups:
      MySqlDatabase::create()->setChunkSize(100000);
      

Debugging

  1. Verbose Output:

    php artisan backup:run --verbose
    
    • Shows detailed logs for each step (e.g., file copying, database dumping).
  2. Log Files:

    • Check storage/logs/laravel-backup.log for errors.
    • Enable debug mode in config/backup.php:
      'debug' => env('BACKUP_DEBUG', false),
      
  3. Dry Runs:

    • Test configurations without writing files:
      php artisan backup:run --test
      
  4. Manual Cleanup:

    • Force cleanup for a specific destination:
      php artisan backup:clean --destination=local
      

Configuration Quirks

  1. Default Destinations:

    • If no destinations are configured, backups are not saved. Always define at least one.
  2. Database Credentials:

    • Use Laravel’s .env variables for security:
      MySqlDatabase::create()
          ->setUsername(env('DB_USERNAME'))
          ->setPassword(env('DB_PASSWORD'));
      
  3. Overwriting Backups:

    • By default, backups are not overwritten. Use BackupDestination::overwrite() to force:
      BackupDestination::create('s3')->overwrite();
      
  4. Parallel vs. Sequential:

    • Destinations are processed in parallel by default. Use BackupDestination::sequential() to process one at a time:
      BackupDestination::create('s3')->sequential();
      
  5. Custom Backup Names:

    • Override naming convention:
      'name' => 'myapp_backup_' . date('Y-m-d'),
      

Extension Points

  1. Custom Tasks:

    • Add tasks to the pipeline in config/backup.php:
      'tasks' => [
          \Spatie\Backup\Tasks\Backup\CreateBackup::class,
          \App\Tasks\CustomTask::class, // Your custom logic
          \Spatie\Backup\Tasks\Backup\Notify::class,
      ],
      
    • Implement Spatie\Backup\Tasks\Task interface.
  2. Custom Destinations:

    • Extend Spatie\Backup\BackupDestination\BackupDestination
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony