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

Create ZIP backups of your Laravel app: selected files plus database dumps. Store backups on any Laravel filesystem (including multiple destinations), monitor backup health, send notifications on failures, and automatically clean up old backups to save space.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

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

    Publish the config file to customize settings.

  2. First Backup: Run the backup command:

    php artisan backup:run
    

    This creates a zip file containing your specified files and databases, stored on the configured disk (default: local).

  3. Key Configurations:

    • Define source.files.include to specify directories/files to back up (e.g., base_path()).
    • Configure source.databases to include/exclude database connections (e.g., ['mysql']).
    • Set destination.disks to store backups on multiple disks (e.g., ['local', 's3']).

First Use Case: Scheduled Backups

Use Laravel’s task scheduler (app/Console/Kernel.php) to automate backups:

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

Run php artisan schedule:run manually or let Laravel handle it via cron.


Implementation Patterns

1. Customizing Backup Sources

  • Dynamic File Inclusion: Use Laravel’s config() or environment variables to dynamically set source.files.include:
    'include' => [
        base_path(),
        config('backup.custom_paths.storage'),
    ],
    
  • Database-Specific Dumps: Customize dumps per connection in config/database.php:
    'mysql' => [
        'dump' => [
            'exclude_tables' => ['sessions', 'failed_jobs'],
            'useSingleTransaction' => true,
        ],
    ],
    

2. Multi-Destination Backups

Store backups on multiple disks (e.g., local + S3 + FTP):

'destination' => [
    'disks' => ['local', 's3', 'backup-ftp'],
],

Configure disks in config/filesystems.php.

3. Encrypted Backups

Enable encryption in config/backup.php:

'password' => env('BACKUP_PASSWORD'),
'encryption' => 'aes256',

4. Cleanup Old Backups

Automate cleanup via scheduler:

$schedule->command('backup:clean')->weekly();

Configure retention in config/backup.php:

'cleanup' => [
    'prune_backups_after_days' => 30,
    'prune_backups_before_days' => 7,
],

5. Monitoring Backups

Check backup health with:

php artisan backup:monitor

Set up notifications (e.g., Slack, Email) in config/backup.php:

'notifications' => [
    'notifiable' => \App\Notifications\BackupFailed::class,
    'channels' => ['mail', 'slack'],
],

6. Zero-Downtime Deployments

Exclude storage/framework and follow symlinks:

'source' => [
    'files' => [
        'follow_links' => true,
        'exclude' => [storage_path('framework')],
    ],
],

Gotchas and Tips

Pitfalls

  1. Permission Issues:

    • Ensure the backup user has read/write access to source.files.include paths and temporary_directory.
    • For S3/remote disks, verify IAM permissions and credentials.
  2. Large Database Dumps:

    • Use database_dump_compressor (e.g., Spatie\DbDumper\Compressors\GzipCompressor) to reduce size.
    • For MySQL, enable useSingleTransaction to avoid table locks:
      'dump' => ['useSingleTransaction' => true],
      
  3. Symlink Handling:

    • Set follow_links: true to include symlinked directories (e.g., storage_path()).
    • Otherwise, symlinks are stored as broken links in the zip.
  4. Temporary Directory Space:

    • Monitor temporary_directory (default: storage/app/backup-temp) for disk space.
    • Clean up manually if needed:
      php artisan backup:clean --force
      
  5. Verification Overhead:

    • Disable verify_backup: true for non-critical backups to speed up the process.
  6. Multi-Disk Failures:

    • Set continue_on_failure: true to keep running if one disk fails (e.g., S3 outage).

Debugging Tips

  1. Dry Runs: Use --dry-run to preview what will be backed up:

    php artisan backup:run --dry-run
    
  2. Logging: Enable verbose output:

    php artisan backup:run --verbose
    

    Check logs in storage/logs/laravel.log.

  3. Manual Cleanup: Force cleanup of old backups:

    php artisan backup:clean --force
    
  4. Database Dump Issues:

    • For MySQL, ensure mysqldump is installed on the server.
    • Test database dumps separately:
      php artisan db:dump --connection=mysql
      

Extension Points

  1. Custom Compressors: Extend Spatie\DbDumper\Compressors\Compressor for custom compression (e.g., Brotli):

    class BrotliCompressor implements Compressor {
        public function compress(string $content): string { ... }
    }
    

    Register in config/backup.php:

    'database_dump_compressor' => \App\Compressors\BrotliCompressor::class,
    
  2. Pre/Post Backup Hooks: Use Laravel’s events to run logic before/after backups:

    // In EventServiceProvider
    protected $listen = [
        'backup.starting' => [YourBackupHandler::class, 'handle'],
    ];
    
  3. Custom Destinations: Implement Spatie\Backup\Tasks\Destination\Destination to add new storage backends (e.g., Backblaze B2):

    class B2Destination implements Destination { ... }
    

    Register in config/backup.php:

    'destination' => [
        'disks' => ['local', 'b2'],
    ],
    
  4. Dynamic Config: Override config dynamically in a service provider:

    public function boot() {
        config(['backup.source.files.include' => [base_path(), config('custom.backup.path')]]);
    }
    

Pro Tips

  1. Backup Metadata: Use backup:monitor to track backup health (e.g., size, duration, errors).

  2. Offsite Backups: Combine local + remote disks (e.g., local + s3) for redundancy.

  3. Incremental Backups: For large databases, consider tools like mysqldump --where or pg_dump --incremental (requires custom implementation).

  4. Backup Testing: Periodically restore backups to a staging environment to verify integrity.

  5. Environment-Specific Config: Use backup.php environment variables:

    'disks' => env('BACKUP_DISKS', ['local']),
    
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