Hi, folks am happy to share this with you as you already know how backing up your database is very important to avoid data loss, if you are looking for a way to backup your database using Laravel version 5 to 8, you are at the right place. At the end of this article I will provide the source code, GitHub repo and youtube video to make sure I put you through without facing any challenges, and if you face any don't forget to reach me via the comment box.
How you will learn
- How to backup your database
- Delete old files to free up space
- send notification
following this tutorial, you will first install a fresh laravel app or use your old laravel app.
if you are coming from using the fresh laravel app do this, if you are not skip.
Install via Laravel global command
laravel new database_backup --git
or install via composer command
composer create-project laravel/laravel database_backup
The next step is for fresh installation and old projects
go to app/config.php to setup data that we will use to access the database for the backup
'db_username' => env('DB_USERNAME'),
'db_password' => env('DB_PASSWORD'),
'db_host' => env('DB_HOST'),
'db_database' => env('DB_DATABASE'),
create backup database command using
php artisan make:command BackupDatabase
A new file will be created under this folder app\Console\Commands\BackupDatabase.php, open it and paste this code snippet
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
class BackupDatabase extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
//call it with php artisan backup:db to run the code
protected $signature = 'backup:db';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct() {
parent::__construct();
//calling it from the config we added before
$this->host = config('app.db_host');
$this->user = config('app.db_username');
$this->pass = config('app.db_password');
$this->dbname = config('app.db_database');
}
/**
* Execute the console command.
*
* @return int
*/
public function handle() {
//code that will handle the backup
try {
//path directory to store the file
$storePath = storage_path() . '/app/backup';
//filename , name of the file
$filename = 'backup' . Carbon::now()->format('Y_m-d') . '.sql';
//check if the path directory exist and skip if not create it before procceeding
if (!is_dir(dirname($storePath))) {
//we create fuction to create the path
static::createPathDiretory($storePath);
}
//handling the backup
$command = "mysqldump --user=" . $this->user . " --password=" . $this->pass . " --host=" . $this->host . " " . $this->dbname . " > " . $storePath . $filename;
$returnVar = null;
$output = null;
exec($command, $output, $returnVar);
//adding function to delete old files after successfully backup of new files
$time = 345600; //time is in seconds eg 4 days = 345600 , delete file after 4 days
//function to handle delete file
static::deleteOldFiles($storePath, $time);
//send notification after successful backup
//send notification to email using your already mailling functions
} catch (Exception $ex) {
//backup fails
//send notification to email using your already mailling functions
}
}
public static function createPathDiretory($path_dir, $abs = true) {
if (!is_dir($path_dir)) {
//create the path with permission to read and write
mkdir($path_dir, 0777, true);
}
return ($abs ? $path_dir : $path_dir);
}
public static function deleteOldFiles($storePath, $time) {
//loop into the directory and put all the files in foreach to check
foreach (glob($storePath . "*") as $file) {
//check the file that its time is more than 4 days depends on your own time
if (time() - filectime($file) > $time) {
unlink($file);
}
}
}
}
to test the code on your live server use php artisan backup:db
Next step, we need to add it for automation to avoid accessing it always from terminal
locate app\Console\Kernel.php
use App\Console\Commands\BackupDatabase;
protected $commands = [
//adding the backup to laravel schedule
BackupDatabase::class
];
protected function schedule(Schedule $schedule)
{
//depends on your need
$schedule->command('backup:db')->daily();
//go to your cpanel, cron job and add this command// /usr/local/bin/php /home/hostusername/root folder/artisan schedule:run >> /dev/null 2>&1
}
The last step go to your cpanel, cron job and add this command
/usr/local/bin/php /home/hostusername/root folder/artisan schedule:run >> /dev/null 2>&1
Congratulations you have successfully learned how to backup your database, find this article and resources helpful kindly share and comment, it will encourage me to write more on laravel and other languages.
Github link: Backupdatabase
Be first to comment