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

Back up your Laravel app to any configured filesystem. Creates zip archives of selected files plus database dumps, supports multiple destinations, health monitoring, notifications, and automated cleanup of old backups via simple Artisan commands.

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
    
    • Verify config/backup.php is published and configured.
  2. First Backup

    php artisan backup:run
    
    • Defaults to backing up base_path() (excluding vendor, node_modules, and storage/framework) and the primary database (DB_CONNECTION).
    • Outputs a zip file to the local disk (configured in config/filesystems.php).
  3. Key Configuration

    • Sources: Modify source.files.include/exclude to customize files/directories.
    • Databases: Adjust source.databases to include/exclude specific connections or tables.
    • Destinations: Update destination.disks to store backups on S3, FTP, etc.

First Use Case: Zero-Downtime Deployment Backup

  1. Configure Storage Symlinks Uncomment storage_path() in source.files.include and set follow_links: true to include symlinked storage directories (e.g., for zero-downtime deployments).

  2. Run Backup Before Deployment

    php artisan backup:run --name="pre-deployment-backup-$(date +%Y-%m-%d)"
    
    • Use --name to tag backups for traceability.
  3. Verify Backup

    php artisan backup:monitor
    
    • Checks if the backup was created successfully and contains expected files.

Implementation Patterns

Core Workflows

1. Scheduled Backups

  • Use Laravel’s Task Scheduling (app/Console/Kernel.php) to automate backups:
    $schedule->command('backup:run')->dailyAt('2:00');
    
  • Pro Tip: Schedule during low-traffic periods to avoid performance impact.

2. Multi-Destination Backups

  • Store backups on multiple disks (e.g., local + S3 + FTP) by configuring destination.disks:
    'disks' => ['local', 's3', 'backup-ftp'],
    
  • Use Case: Offsite backups for disaster recovery.

3. Database-Specific Customizations

  • Exclude sensitive tables (e.g., password_resets) or optimize dumps:
    'mysql' => [
        'dump' => [
            'exclude_tables' => ['password_resets', 'sessions'],
            'useSingleTransaction' => true, // For InnoDB-only MySQL
        ],
    ],
    
  • Reference: Spatie DbDumper Docs.

4. Encrypted Backups

  • Enable encryption in config/backup.php:
    'password' => env('BACKUP_ARCHIVE_PASSWORD'),
    'encryption' => 'aes256',
    
  • Security Note: Store passwords in .env (never hardcode).

Integration Tips

1. Pre/Post-Backup Hooks

  • Use events to extend backup logic:
    // app/Providers/EventServiceProvider.php
    protected $listen = [
        \Spatie\Backup\Events\BackupCreated::class => [
            \App\Listeners\NotifySlackOnBackup::class,
        ],
    ];
    
  • Example: Send Slack notifications or trigger cleanup scripts.

2. Custom Backup Commands

  • Extend the backup command for project-specific logic:
    php artisan backup:run --only=files  # Skip databases
    php artisan backup:run --only=databases  # Skip files
    
  • Advanced: Create a custom command to backup only critical directories:
    php artisan backup:custom --directories=storage/app/public,config
    

3. Monitoring and Alerts

  • Health Checks: Use backup:monitor to verify backups:
    php artisan backup:monitor --health
    
  • Notifications: Configure channels (e.g., Slack, Email) in config/backup.php:
    'notifications' => [
        'notifiable' => \App\Notifications\BackupFailedNotification::class,
        'channels' => ['mail', 'slack'],
    ],
    

4. Cleanup Old Backups

  • Automate retention policies:
    'cleanup' => [
        'mode' => \Spatie\Backup\Tasks\Cleanup::MODE_KEEP_MONTHLY,
        'retain_backups' => 6, // Keep 6 monthly backups
        'retain_days' => 30,   // Delete backups older than 30 days
    ],
    
  • Schedule Cleanup:
    $schedule->command('backup:clean')->weekly();
    

Gotchas and Tips

Pitfalls

1. Permission Issues

  • Symlink Problems: If follow_links: true, ensure the backup user has read permissions for all symlinked directories.
    chmod -R a+rX /path/to/symlinked/directory
    
  • Storage Permissions: For local backups, verify the storage/app/backups directory is writable:
    chmod -R 755 storage/app/backups
    

2. Database Dump Failures

  • Locking Issues: MySQL may lock tables during dumps. Use useSingleTransaction: true for InnoDB-only setups.
  • Large Databases: For databases >1GB, consider:
    • Chunked Dumps: Use Spatie\DbDumper\Compressors\GzipCompressor to reduce file size.
    • Remote Dumps: Offload to a dedicated backup server.

3. Zip Archive Corruption

  • Verify Backups: Enable verify_backup: true to catch silent failures:
    'verify_backup' => true,
    
  • Memory Limits: Large backups may hit PHP’s memory_limit. Increase it temporarily:
    php -d memory_limit=2G artisan backup:run
    

4. Retry Logic

  • Transient Failures: Use tries and retry_delay to handle flaky storage (e.g., S3 timeouts):
    'tries' => 3,
    'retry_delay' => 60, // 60 seconds between retries
    

Debugging Tips

1. Dry Runs

  • Test configurations without creating backups:
    php artisan backup:run --dry-run
    
  • Output: Lists files/databases that would be included.

2. Logging

  • Enable verbose logging for troubleshooting:
    php artisan backup:run --verbose
    
  • Log Location: Check storage/logs/laravel.log for errors.

3. Backup Contents Inspection

  • Extract a backup to verify contents:
    unzip -l storage/app/backups/your-backup.zip
    

Extension Points

1. Custom Backup Tasks

  • Add pre/post-backup tasks via events:
    // Listen for BackupStarting
    BackupStarting::dispatch();
    
  • Example: Run php artisan optimize:clear before backups.

2. Dynamic Configurations

  • Override settings per environment or backup type:
    // In a service provider
    $this->app->singleton(Backup::class, function ($app) {
        $backup = new Backup();
        $backup->setSource(new FilesSource([
            'include' => [base_path('custom-path')],
        ]));
        return $backup;
    });
    

3. Custom Destinations

  • Extend Spatie\Backup\Tasks\Destination\Destination to support custom storage (e.g., custom S3 buckets):
    class CustomS3Destination extends Destination
    {
        public function __construct(string $diskName, string $bucketName)
        {
            $this->disk = Storage::disk($diskName)->buildPath($bucketName);
        }
    }
    

4. Backup Metadata

  • Access backup metadata (e.g., size, duration) in notifications:
    public function toMail(BackupCreated $event)
    {
        return (new MailMessage)
            ->line("Backup created: {$event->backup->name}")
            ->line("Size: {$event->backup->sizeInBytes} bytes")
            ->line("Duration: {$event->backup->duration} seconds");
    }
    

Configuration Quirks

1. Relative Paths in Zip

  • Set relative_path to control paths in the zip file:
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai