Skip to content

Instantly share code, notes, and snippets.

@fmtarif
Last active April 12, 2020 08:13
Show Gist options
  • Save fmtarif/82e5c5ccf7d62f98ca9595548eaa15dd to your computer and use it in GitHub Desktop.
Save fmtarif/82e5c5ccf7d62f98ca9595548eaa15dd to your computer and use it in GitHub Desktop.
#laravel Database dump laravel console command
<?php //from: https://pineco.de/scheduling-mysql-backups-with-laravel/ ?>
<?php
namespace App\Console\Commands;
use File;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
class BackupDatabase extends Command
{
protected $signature = 'db:backup';
protected $description = 'Backup the database';
protected $process;
protected $filepath;
protected $filename;
public function __construct()
{
parent::__construct();
$file = $this->getFilePath();
if (! File::isDirectory($this->filepath)) {
File::makeDirectory($this->filepath, 0755, true);
}
$this->process = new Process(sprintf(
'mysqldump -u%s -p\'%s\' %s > %s',
config('database.connections.mysql.username'),
config('database.connections.mysql.password'),
config('database.connections.mysql.database'),
$file
));
}
public function handle()
{
try {
$this->process->mustRun();
$this->info('The backup has been proceed successfully.');
$this->info(shell_exec('ls -lah ' . $this->getFilePath()));
} catch (ProcessFailedException $exception) {
$this->error('The backup process has been failed, err: ' . $exception->getMessage());
}
}
public function getFilePath()
{
$this->filepath = storage_path('backups');
// $this->filename = 'dbdump_' . time() . '.sql';
$this->filename = 'dbdump_' . now()->format('Y-m-d_h.i.sa_e') . '.sql'; //dbdump_2020-04-12_08.05.46am_UTC.sql
return $this->filepath . '/' . $this->filename;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment