Skip to content

Instantly share code, notes, and snippets.

@mrl22
Created February 5, 2026 17:35
Show Gist options
  • Select an option

  • Save mrl22/7fed242437e5ccfd4c59c10f32826ed0 to your computer and use it in GitHub Desktop.

Select an option

Save mrl22/7fed242437e5ccfd4c59c10f32826ed0 to your computer and use it in GitHub Desktop.
php artisan db:export - Very similar function to wp-cli db:export but for Laravel - Support MySQL and SQLite
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class DbExportCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'db:export';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Export the database to a timestamped SQL file in the project root';
/**
* Execute the console command.
*/
public function handle(): int
{
$connection = config('database.default');
$config = config("database.connections.{$connection}");
if ($config['driver'] === 'mysql' || $config['driver'] === 'mariadb') {
return $this->exportMysql($config);
}
if ($config['driver'] === 'sqlite') {
return $this->exportSqlite($config);
}
$this->error("The {$config['driver']} driver is not supported for export.");
return Command::FAILURE;
}
protected function exportMysql(array $config): int
{
$filename = sprintf('%s-%s.sql', $config['database'], now()->format('Y-m-d-H-i-s'));
$path = base_path($filename);
$command = sprintf(
'mysqldump --user=%s --password=%s --host=%s --port=%s %s > %s',
escapeshellarg($config['username']),
escapeshellarg($config['password']),
escapeshellarg($config['host']),
escapeshellarg($config['port']),
escapeshellarg($config['database']),
escapeshellarg($path)
);
$this->info("Exporting database to {$filename}...");
exec($command, $output, $resultCode);
if ($resultCode === 0) {
$this->info('Database exported successfully.');
return Command::SUCCESS;
}
$this->error('Database export failed.');
return Command::FAILURE;
}
protected function exportSqlite(array $config): int
{
$databasePath = $config['database'];
if (! file_exists($databasePath)) {
$this->error("SQLite database file not found at: {$databasePath}");
return Command::FAILURE;
}
$filename = sprintf('database-%s.sqlite.sql', now()->format('Y-m-d-H-i-s'));
$path = base_path($filename);
$command = sprintf(
'sqlite3 %s .dump > %s',
escapeshellarg($databasePath),
escapeshellarg($path)
);
$this->info("Exporting SQLite database to {$filename}...");
exec($command, $output, $resultCode);
if ($resultCode === 0) {
$this->info('Database exported successfully.');
return Command::SUCCESS;
}
$this->error('Database export failed.');
return Command::FAILURE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment