Laravel Console Command to Automatically Restore a Backup from Spatie Laravel Backup Package

profile picture

Laravel Console Command to Automatically Restore a Backup from Spatie Laravel Backup Package

spatie/laravel-backup is an amazing Laravel Package that allows you to automatically send backups of your laravel application to an AWS S3 Bucket. It's good practice to regularly trigger a "DB only" backup.

What about automatic restore ?

Restoring backup is quite straightforward in term of desired functionnality.

You want to take a specific backup (probably the last one) and import the SQL dump in your actual database.

Weirdly, this feature is not provided by spatie's package.

Solution : a simple command

I made this for one of my project where I basically want to take the last SQL file backup put it in my database.

I personnaly use this locally and never in production.

You can modify it as you please of course.


namespace App\Console\Commands;

use ZipArchive;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;

class RestoreLastBackup extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'backup:restore-last';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Restore the last backup from s3';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // Startup
        $this->info('Restoring backup from s3');

        // Get Last backup file
        $lastFile = collect(Storage::disk($this->getBackupDisk())->allFiles())->last();
        $this->info('Last backup found: ' . $lastFile);

        // Download File
        $this->info('Downloading ZIP file...');

        Storage::disk('local')->writeStream('backups/' . $lastFile, Storage::disk($this->getBackupDisk())->readStream($lastFile));
        $this->info('Zip File downloaded');

        // Unzip
        $this->info('Unzipping file...');
        $success = $this->unzipBackup($lastFile);

        if ($success) {
            $this->info('Unzipping successful !');
            $this->startDump();
        } else {
            $this->error('Zip file not found');
        }
    }

    private function getBackupDisk()
    {
        return config('backup.backup.destination.disks')[0];
    }

    private function getBackupName()
    {
        return config('backup.backup.name');
    }

    private function unzipBackup($file)
    {
        $zip = new ZipArchive;
        $res = $zip->open(
            Storage::disk('local')->path('backups/' . $file)
        );
        if ($res === TRUE) {
            $zip->extractTo(Storage::disk('local')->path('backups/'.$this->getBackupName()));
            $zip->close();
            return true;
        } else {
            return false;
        }
    }

    private function startDump()
    {
        // Wipe Database
        $this->info('Wipe DB...');
        Artisan::call('db:wipe');
        $this->info('Database wiped');

        // Import SQL file
        $this->info('Dumping SQL dump...');
        $sqlFile = Storage::disk('local')->path('backups/'.$this->getBackupName().'/db-dumps/mysql-'.config('database.connections.mysql.database').'.sql');

        // Files is sometimes too big to be imported with PHP, so we run a mysql command instead
        if (config('database.mysql.password')) {
            exec("mysql -u ".config('database.connections.mysql.username')." -p".config('database.connections.mysql.password')." ".config('database.connections.mysql.database')." < " . $sqlFile);
        } else {
            exec("mysql -u ".config('database.connections.mysql.username')." ".config('database.connections.mysql.database')." < " . $sqlFile);
        }

        $this->info('Done !');
    }
}
laravel
sql
spatie
backup
restore
s3
aws
amazon
mysql
console
command

about me

profile picture

I consider myself as an IT Business Artisan. Or Consultant CTO. I'm a self-taught Web Developper, coach and teacher. My main work is helping and guiding digital startups.

more about me

follow me

newsletter

A weekly email with the latests articles

support my work

Start trading on binance
  • BTC

    BTC

    18SY81ejLGFuJ9KMWQu5zPrDGuR5rDiauM

  • ETH

    ETH

    0x68e8c828b8ce670062a83199cd8f62667c792f23

  • Monero

    XMR

    895bSneY4eoZjsr2hN2CAALkUrMExHEV5Pbg8TJb6ejnMLN7js1gLAXQySqbSbfzjWHQpQhQpvFtojbkdZQZmM9qCFz7BXU

(adsbygoogle = window.adsbygoogle || []).push({});

2022 © My Dynamic Production SRL All rights Reserved.