Skip to content

Instantly share code, notes, and snippets.

@emyasnikov
Forked from phillipsharring/Kernel.php
Last active July 29, 2021 09:00
Show Gist options
  • Save emyasnikov/f6d35a8c0210f0ddef475fd815949542 to your computer and use it in GitHub Desktop.
Save emyasnikov/f6d35a8c0210f0ddef475fd815949542 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
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('mysql:dump')->weekly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MySqlDumpCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mysql:dump';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run mysqldump using environment variables';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$database = env('DB_DATABASE');
$host = env('DB_HOST');
$password = env('DB_PASSWORD');
$username = env('DB_USERNAME');
$separator = DIRECTORY_SEPARATOR;
$password = $password ? " -p {$password}" : '';
$file = date('Y-m-d-His-', time()) . $database . '.sql';
$path = database_path() . $separator . 'dump' . $separator;
$command = sprintf("mysqldump -h %s -u %s %s %s > %s", $host, $username, $password, $database, $path . $file);
if (!is_dir($path)) {
mkdir($path, 0722, true);
}
exec($command);
$this->info("Created MySQL dump: {$file}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment