DEV Community

Cover image for Laravel - Automate Database Backup
Chandresh Singh
Chandresh Singh

Posted on

Laravel - Automate Database Backup

Backup your database and automate the process using this simple method.

If you want to watch me doing it then below is the tutorial video for the same.

Let’s Start!

Pull in the package “laravel-backup” using composer.

composer require spatie/laravel-backup

Publish config file using this command.

php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"

Open backup.php inside config folder.

There are a bunch of configuration settings here:

In the source, Write your file path or directory that you want to include or exclude from backup.

Write the database connection name which you want to backup.

Within destination, Write disk name on which you want to store backups.

If you want to store them in AWS S3 then you can define your disk in filesystems.php.

For using S3, pull in the package "league/flysystem-aws-s3-v3"

composer require "league/flysystem-aws-s3-v3"

Write your S3 access credentials in .env file.

Select the notifications that you want to receive and Write your email id on which you want to receive your notification.

You can even get these notification on slack as well.

Configure email service if you haven’t from mail.php and write mail service credentials in .env file.

Set the no of days you want your backups to kept and deleted automatically after a certain time period.

Schedule these commands using Laravel Scheduler. For that Open app/Console/Kernel.php and write these inside schedule function.

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

Set your Laravel Scheduler to run every minute using either crontab or supervisor.

For crontab, it should look something like this.

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

Alt Text

That's It!

All your backups now will be stored and you will be notified on email or slack and old backups will also be deleted automatically as configured by you in backup.php.

Discussion (1)

Collapse
skozeniuk profile image
SashaKozeniuk • Edited on

Make a backup copy regularly, because the more often you make a backup, the less work you will have to do after recovery. I found a great tool for this purpose here