Simple Laravel Backup Tidy

Written by Rich Banks on 21st Dec, 2015

Laravel

If you are saving your database backups to cloud storage such as Amazon s3 as shown in my previous article Simple Laravel Backup, you may want to remove old backups to keep your directory tidy and lower storage space. Doing this in Laravel is really simple.

Create a new console command file named BackupTidy.php in app/Console/Commands.

php artisan make:console BackupTidy

Open the newly created file and change the signature as below:

protected $signature = 'backup:tidy';

Add a console command description. See example below:

protected $description = 'Remove backup files that are over one month old.';

We will be using Carbon and Storage in the class so define it at the top of your document.

use Carbon;
use Storage;

In the handle method we can add our code

public function handle()
{
    //get all files in the backup directory of your s3 storage
    $files = Storage::disk('s3')->files('backups');

    foreach($files as $file){

        //get last modified date of file
        $modified = Storage::disk('s3')->lastModified($file);
        //create a carbon instance of the last modified unix timestamp
        $date     = Carbon\Carbon::createFromTimestampUTC($modified);

        //if the file date is over one month old
        if($date < Carbon\Carbon::now()->subMonth(1)){

            //delete file
            Storage::disk('s3')->delete($file);
            //output to console deleted filename
            $this->info("Deleted " . $file);

        }

    }

}

You can change the length of time you keep backups for by changing Carbon\Carbon::now()->subMonth(1). For more information about Carbon add and subtraction please visit carbon.nestbot.com

Open app/Console/Kernel.php and add your class to the protected commands

protected $commands = [
        \App\Console\Commands\Inspire::class,
        \App\Console\Commands\BackupDatabase::class,
        \App\Console\Commands\BackupTidy::class,
    ];

You can now run your backup tidy command by typing the below artisan command:

php artisan backup:tidy

Laravel makes it easy to schedule your newly created console command to run automatically. To do this add the below inside the schedule method of app/Console/Kernel.php

$schedule->command('backup:tidy')->dailyAt('1:00');

This command will run at 1am each day.

For more scheduling options and information about setting up your schedule, please take a look at laravel.com

Files for this article can be found on GitHub

If you would like to be able to restore your database from one of your backups from the Laravel console take a look at my next article Simple Laravel Restore.