Automate your database backups with Laravel: A comprehensive guide

Automate your database backups with Laravel: A comprehensive guide

👋 Hello everyone!

🚀 Today, we’ll explore how to automate database backups using Laravel.

📁 The backup consists of a zip file containing all specified directories’ files and a database dump. Store it on any of your configured filesystems. Plus, receive notifications via E-mail, Slack, or any provider if something goes wrong with your backups.

Let’s dive in!

1. – Composer package installation

composer require spatie/laravel-backup

To publish the config file to config/backup.php run:

php artisan vendor:publish provider=“SpatieBackupBackupServiceProvider”

2. Database backup execution

php artisan backup:run

3. MySQL clients installation

🐧 For Arch Linux users:
sudo pacman -S mysql-clients

🐧 For Ubuntu/Debian users:
sudo apt-get install mysql-client

💻 For macOS users:
brew install mysql-client

💻 For Windows users: Install MySQL Installer

4. Commands execution

php artisan storage:link
php artisan backup:run

Voila!

📂 Locate the dumped zip inside storage/app/Laravel directory. You can modify this export path location in the exported config file found in config/backup.php.

🗓️ As you can observe, the format is 2024-06-02-16-01-40.zip. You can adjust this in the configuration file on line.

Additional

Cleanup old backups

//config/backup.php

‘cleanup’ => [
/*
* The strategy that will be used to cleanup old backups. The default strategy
* will keep all backups for a certain amount of days. After that period only
* a daily backup will be kept. After that period only weekly backups will
* be kept and so on.
*
* No matter how you configure it the default strategy will never
* deleted the newest backup.
*/

‘strategy’ => SpatieBackupTasksCleanupStrategiesDefaultStrategy::class,

‘default_strategy’ => [

/*
* The number of days that all backups must be kept.
*/

‘keep_all_backups_for_days’ => 7,

/*
* The number of days that all daily backups must be kept.
*/

‘keep_daily_backups_for_days’ => 16,

/*
* The number of weeks of which one weekly backup must be kept.
*/

‘keep_weekly_backups_for_weeks’ => 8,

/*
* The number of months of which one monthly backup must be kept.
*/

‘keep_monthly_backups_for_months’ => 4,

/*
* The number of years of which one yearly backup must be kept.
*/

‘keep_yearly_backups_for_years’ => 2,

/*
* After cleaning up the backups remove the oldest backup until
* this amount of megabytes has been reached.
* Set null for unlimited size.
*/

‘delete_oldest_backups_when_using_more_megabytes_than’ => 5000,
],
],

Use the following command:
php artisan backup:clean

Sending notifications

Visit official package documentation page

MySQL Clients Installation🙏 Thank you for reading my blog post! Hope you found it helpful.

👉 Follow me on GitHub for more updates!