Laravel Database Backup — Backup & Mail

A minimalist implementation using Spatie’s laravel-backup package

Photo by Kevin Ku on Unsplash

Some technical details about my local setup — just for reference

Spatie who?!—

The Implementation

composer require guzzlehttp/guzzle

Step 1 — Install the package via composer:

composer require spatie/laravel-backup

Step 2 — publish the package’s configuration file with:

php artisan vendor:publish — provider=”Spatie\Backup\BackupServiceProvider”
‘mail’ => [
‘to’ => ‘your@example.com’,
],
‘mail’ => [
‘to’ => env(‘DB_BACKUP_EMAIL’),
],
/*
* The list of directories and files that will be included in the backup.
*/
‘include’ => [
// base_path(),
],

Step 3 — schedule backup operation(s)

$schedule->command(‘backup:clean’)->daily()->at(‘01:00’);
$schedule->command(‘backup:run’)->daily()->at(‘02:00’);

Quick Test

php artisan backup:run

Step 4 — listen for Spatie\Backup\Events\BackupZipWasCreated

php artisan make:listener MailSuccessfulDatabaseBackup -e \Spatie\Backup\Events\BackupZipWasCreated
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
\Spatie\Backup\Events\BackupZipWasCreated::class => [
MailSuccessfulDatabaseBackup::class
],
];
<?php

namespace
App\Listeners;

// use Illuminate\Contracts\Queue\ShouldQueue;
// use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Mail;
use Spatie\Backup\Events\BackupZipWasCreated;

class MailSuccessfulDatabaseBackup
{
/**
* Create the event listener.
*
*
@return void
*/
public function __construct()
{
//
}

/**
* Handle the event.
*
*
@param BackupZipWasCreated $event
*
@return void
*/
public function handle(BackupZipWasCreated $event)
{
$this->mailBackupFile($event->pathToZip);
}

public function mailBackupFile($path)
{
try {
Mail::raw('You have a new database backup file.', function ($message) use ($path) {
$message->to(env('DB_BACKUP_EMAIL'))
->subject('DB Auto-backup Done')
->attach($path);
});
} catch (\Exception $exception) {
throw $exception;
}

}
}

Long story short —

Extra Sauce:

Route::get('/backup', function () {

\Illuminate\Support\Facades\Artisan::call('backup:run');

return 'Successful backup!';

});

Associated Github branch:

Human & software engineer. Interested in ()=> {[Arts, Education, Music, Science, Tech, AI, co-Humans]};