Skip to content

Instantly share code, notes, and snippets.

@Patabugen
Forked from phillipsharring/Kernel.php
Last active October 9, 2023 13:12
Show Gist options
  • Save Patabugen/10653ea4820aea5e601723c4cad12e7a to your computer and use it in GitHub Desktop.
Save Patabugen/10653ea4820aea5e601723c4cad12e7a to your computer and use it in GitHub Desktop.
Laravel Artisan command to perform MySQL Dump using database connection information in the .env file. Posted 2016 Jan. Unsupported. 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 = config('database.connections.mysql.host');
$username = config('database.connections.mysql.username');
$password = config('database.connections.mysql.password');
$database = config('database.connections.mysql.database');
$port = config('database.connections.mysql.port');
$process = new Process([
'mysqldump',
'-h', $host,
'-P', $port,
'-u', $username,
'-p'.$password,
$database,
]);
$process->run();
// Note: I actually use Storage::put() and a fixed filename to output, but for consistency with the rest of this Gist I've
// put this untested version in:
$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';
file_put_contents($path, $process->getOutput());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment