Setting of Auto backup of Mysql database in a laravel project
Bhavani
- 0
1. Create a Laravel Artisan Command
- Run the following command to create a custom Artisan command:
php artisan make:command BackupDatabase
- Open the generated file in
app/Console/Commands/BackupDatabase.phpand update its content:<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;class BackupDatabase extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = ‘backup:database’;/**
* The console command description.
*
* @var string
*/
protected $description = ‘Backup the MySQL database’;/**
* Execute the console command.
*/
public function handle()
{
$dbName = env(‘DB_DATABASE’);
$dbUser = env(‘DB_USERNAME’);
$dbPassword = env(‘DB_PASSWORD’);
$dbHost = env(‘DB_HOST’, ‘127.0.0.1’);$backupPath = storage_path(‘app/backups/’ . date(‘Y-m-d_H-i-s’) . ‘_backup.sql’);
// Ensure the backup directory exists
Storage::makeDirectory(‘backups’);$command = sprintf(
‘mysqldump -u%s -p%s -h%s %s > %s’,
escapeshellarg($dbUser),
escapeshellarg($dbPassword),
escapeshellarg($dbHost),
escapeshellarg($dbName),
escapeshellarg($backupPath)
);$result = null;
$output = null;exec($command, $output, $result);
if ($result === 0) {
$this->info(‘Database backup created successfully: ‘ . $backupPath);
} else {
$this->error(‘Failed to create database backup.’);
}
}
}
2. Schedule the Command in Laravel
- Open the
app/Console/Kernel.phpfile. - Register the new command in the
schedulemethod:protected function schedule(Schedule $schedule){
$schedule->command('backup:database')->dailyAt('02:00');
}
This schedules the backup to run daily at 2:00 AM. Adjust the time as needed.
3. Set Up the Cron Job
- Open the cron jobs configuration file:
crontab -e
- Add the following line to execute Laravel’s scheduler every minute:
* * * * * php /path-to-your-laravel-project/artisan schedule:run >> /dev/null 2>&1
Replace
/path-to-your-laravel-projectwith the actual path to your Laravel application.
4. Verify Backup Files
- The backups will be stored in the
storage/app/backupsdirectory. - Ensure the directory is writable by the web server and the Laravel application.
5. Additional Suggestions
- Compression: Modify the command to compress the backup:
$command = sprintf(
'mysqldump -u%s -p%s -h%s %s | gzip > %s.gz',
escapeshellarg($dbUser),
escapeshellarg($dbPassword),
escapeshellarg($dbHost),
escapeshellarg($dbName),
escapeshellarg($backupPath)
);
- Cloud Storage: Use Laravel’s filesystem to store the backups on S3, Google Cloud Storage, etc.
