-
-
Save phillipsharring/fb500556e7173a1c222d 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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... | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
Thanks @philharmonie !
Curiously I had the same error that you were getting (Access Denied) but when I switched to using the Symfony process control it worked as expected 🤷♀️ This does mean I load the whole file into memory, which could be an issue with large databases.
My slightly different version, using config instead of env and adding the port (because I have a custom port).
A bonus of using Process is that we could also check if it worked, and do something differently if it didn't.