Skip to content

Instantly share code, notes, and snippets.

@PanjiNamjaElf
Forked from phillipsharring/Kernel.php
Created December 24, 2020 02:18
Show Gist options
  • Save PanjiNamjaElf/646e8c1147b2e7576ea32314bb5228a9 to your computer and use it in GitHub Desktop.
Save PanjiNamjaElf/646e8c1147b2e7576ea32314bb5228a9 to your computer and use it in GitHub Desktop.
Laravel Artisan command to perform MySQL Dump using database connection information in the .env file. Forked from https://gist.github.com/kkiernan/bdd0954d0149b89c372a
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
\App\Console\Commands\Inspire::class,
// add the MySqlDump command here
\App\Console\Commands\MySqlDump::class,
];
// etc...
}
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MySqlDump extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'db:dump';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Runs the mysqldump utility using info from .env';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$ds = DIRECTORY_SEPARATOR;
$host = env('DB_HOST');
$username = env('DB_USERNAME');
$password = env('DB_PASSWORD');
$database = env('DB_DATABASE');
$ts = time();
$path = database_path() . $ds . 'backups' . $ds . date('Y', $ts) . $ds . date('m', $ts) . $ds . date('d', $ts) . $ds;
$file = date('Y-m-d-His', $ts) . '-dump-' . $database . '.sql';
$command = sprintf('mysqldump -h %s -u %s -p\'%s\' %s > %s', $host, $username, $password, $database, $path . $file);
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
exec($command);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment