Skip to content

Instantly share code, notes, and snippets.

@nunomaduro
Created January 2, 2018 20:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nunomaduro/7b52a44cfac61d9a9c7316ea78619594 to your computer and use it in GitHub Desktop.
Save nunomaduro/7b52a44cfac61d9a9c7316ea78619594 to your computer and use it in GitHub Desktop.
<?php
namespace App\Commands;
use Illuminate\Console\Scheduling\Schedule;
use LaravelZero\Framework\Commands\Command;
use Illuminate\Support\Facades\Storage;
class BackupCommand extends Command
{
const MAX_FILES = 31;
protected $signature = 'backup';
protected $description = 'Pseudo-code of a command that performs a daily backup of an database.';
public function handle(): void
{
// Step 1: Perform the physical backup of the database.
shell_exec('mysqldump --single-transaction --skip-lock-tables -u {user_name} {database_name} | gzip > ' . storage_path('{file_name}.sql.gz'));
// Step 2: Copy the backup to an external disk / server.
Storage::disk('backup')->put('{file_name}.sql.gz', Storage::get('{file_name}.sql.gz'));
// Step 3: Remove any old backups on the external disk / server.
if ($filesCollection = collect(Storage::disk('backup')->files()) > static::MAX_FILES) {
Storage::disk('backup')->delete($filesCollection->sort()->first());
}
// Step 4: Delete the local copy of the backup.
Storage::delete('{file_name}.sql.gz');
}
public function schedule(Schedule $schedule): void
{
$schedule->command(static::class)->daily();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment