oluokunkabiru / database-exporter
Simple and elegant PHP/Laravel database exporter package that exports databases to SQL files and downloads them locally without phpMyAdmin login.
Package info
github.com/oluokunkabiru/database-exporter
pkg:composer/oluokunkabiru/database-exporter
Requires
- php: >=8.0
- illuminate/support: ^9.0|^10.0|^11.0|^12.0|^13.0
Requires (Dev)
- phpunit/phpunit: ^10.0
README
A powerful Laravel/PHP package that allows you to export and download database backups without needing access to phpMyAdmin or terminal commands.
Features
- 🎯 Export entire database or specific tables
- 📥 Download SQL files directly to your machine or store in cloud
- 🚀 Simple web-based UI with Livewire components
- 💻 CLI commands for automated backups and scheduling
- 🔒 Support for Laravel and vanilla PHP connections
- ⚙️ Configurable export options (compression, formatting, DROP TABLE statements)
- 📊 Real-time export progress tracking
- 🎨 Clean and intuitive TailwindCSS dashboard interface
- 💾 Multiple export formats: SQL, CSV
- 🗜️ Built-in compression support (ZIP)
- 👁️ Include views, triggers, and stored procedures
Installation
Step 1: Install via Composer
composer require oluokunkabiru/database-exporter
Step 2: Publish Configuration (Laravel only)
php artisan vendor:publish --tag=database-exporter-config
Step 3: Publish Views (optional)
php artisan vendor:publish --tag=database-exporter-views
Quick Start
Laravel - Web Interface
- Visit
/database-exporterin your browser - Select tables to export
- Configure export options
- Click "Start Export"
- Download the file
Laravel - CLI Command
# Export entire database as SQL php artisan db:export # Export specific tables php artisan db:export --tables=users,posts,comments # Export as CSV (creates ZIP) php artisan db:export --format=csv # Compress the export php artisan db:export --compress # Include views and triggers php artisan db:export --include-views --include-triggers # Without DROP TABLE statements php artisan db:export --no-drop # All options combined php artisan db:export \ --tables=users,posts \ --format=sql \ --compress \ --include-views \ --include-triggers # Specify output filename php artisan db:export --output=backup-2024.sql
Laravel - Programmatic Usage
use Oluokunkabiru\DatabaseExporter\DatabaseExporter; use Oluokunkabiru\DatabaseExporter\ConnectionResolver; // Automatically detect connection $exporter = new DatabaseExporter(ConnectionResolver::resolve()); // Export entire database $filepath = $exporter ->compress(true) ->addDropTable(true) ->export(); echo "Backup saved to: " . $filepath; // Export specific tables $filepath = $exporter ->tables(['users', 'posts', 'comments']) ->format('csv') ->export(); // Get database information $info = $exporter->getDatabaseInfo(); echo "Database: " . $info['name']; echo "Tables: " . $info['table_count']; echo "Size: " . $info['size_formatted'];
Vanilla PHP - Manual Connection
require 'vendor/autoload.php'; use Oluokunkabiru\DatabaseExporter\DatabaseExporter; use PDO; $connection = new PDO( 'mysql:host=localhost;dbname=my_database;charset=utf8mb4', 'root', 'password', [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ] ); $exporter = new DatabaseExporter($connection); $filepath = $exporter ->tables(['users', 'posts']) ->format('sql') ->compress(true) ->export(); echo "Export completed: " . basename($filepath);
Vanilla PHP - Environment-based Connection
require 'vendor/autoload.php'; use Oluokunkabiru\DatabaseExporter\ConnectionResolver; use Oluokunkabiru\DatabaseExporter\DatabaseExporter; // Set environment variables $_ENV['DB_HOST'] = 'localhost'; $_ENV['DB_PORT'] = 3306; $_ENV['DB_DATABASE'] = 'my_database'; $_ENV['DB_USERNAME'] = 'root'; $_ENV['DB_PASSWORD'] = ''; // Automatically resolve connection $connection = ConnectionResolver::resolveFromEnv(); $exporter = new DatabaseExporter($connection); $filepath = $exporter->export();
Configuration
Edit config/database-exporter.php to customize:
return [ // Enable/disable the web dashboard 'dashboard_enabled' => true, // Route prefix for dashboard 'route_prefix' => 'database-exporter', // Default export format (sql or csv) 'default_format' => 'sql', // Enable compression by default 'enable_compression' => true, // Directory where exports are stored 'backup_directory' => storage_path('exports'), // Include database views 'include_views' => false, // Include database triggers 'include_triggers' => false, // Include stored procedures 'include_procedures' => false, // Add DROP TABLE statements 'add_drop_table' => true, // SQL formatting (pretty or minified) 'sql_format' => 'pretty', // Max execution time in seconds 'max_execution_time' => 900, // Require authentication 'require_auth' => true, // Allowed roles (empty = all authenticated users) 'allowed_roles' => ['admin', 'super_admin'], ];
Usage Examples
Scheduled Backups
// In app/Console/Kernel.php protected function schedule(Schedule $schedule) { $schedule->call(function () { $exporter = app('database-exporter'); $filepath = $exporter ->compress(true) ->export(); // Store in cloud Storage::disk('s3')->put( 'backups/database-' . date('Y-m-d-His') . '.zip', file_get_contents($filepath) ); // Clean old backups $this->deleteOldBackups(); })->daily()->at('02:00'); } protected function deleteOldBackups() { $backupDir = storage_path('exports'); $thirtyDaysAgo = time() - (30 * 24 * 60 * 60); foreach (glob($backupDir . '/*') as $file) { if (filemtime($file) < $thirtyDaysAgo) { unlink($file); } } }
API Endpoint
// In routes/api.php Route::middleware('auth:sanctum')->group(function () { Route::post('/export', function (Request $request) { $exporter = app('database-exporter'); $filepath = $exporter ->tables($request->input('tables', [])) ->format($request->input('format', 'sql')) ->compress($request->boolean('compress', true)) ->export(); return response()->download($filepath); }); });
Available Methods
Configuration Methods
| Method | Description | Type |
|---|---|---|
setConnection(PDO $connection) |
Set database connection | self |
setDatabase(string $database) |
Set database name | self |
tables(array $tables) |
Select specific tables | self |
format(string $format) |
Set export format (sql, csv) | self |
compress(bool $compress) |
Enable/disable compression | self |
includeViews(bool $include) |
Include database views | self |
includeTriggers(bool $include) |
Include triggers | self |
addDropTable(bool $add) |
Add DROP TABLE statements | self |
sqlFormat(string $format) |
Set SQL formatting (pretty, minified) | self |
Query Methods
| Method | Description | Return |
|---|---|---|
getDatabaseInfo() |
Get database information | array |
getAllTables() |
Get all table names | array |
getTableInfo(string $table) |
Get table information | array |
export(?string $filename, ?callable $progressCallback) |
Export database | string (filepath) |
Security
- ✅ Authentication required by default (configurable)
- ✅ Role-based access control
- ✅ File path validation (prevents directory traversal)
- ✅ Database connection validation
- ✅ Temporary file cleanup
Performance
- ⚡ Optimized for large databases
- ⚡ Batch inserts (100 rows per batch)
- ⚡ Progress callbacks for UI updates
- ⚡ Streaming downloads (no memory overload)
- ⚡ Optional compression for smaller files
Troubleshooting
"Database connection not set"
Make sure you're passing a valid PDO connection or using ConnectionResolver::resolve().
Export takes too long
- Increase
max_execution_timein config - Export specific tables instead of entire database
- Use compression to speed up downloads
"File not found" on download
Make sure the backup directory exists and has write permissions:
mkdir -p storage/exports chmod 755 storage/exports
Connection refused
Verify your database credentials in .env:
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=root
DB_PASSWORD=password
Requirements
- PHP >= 8.0
- Laravel >= 9.0 (for Laravel integration)
- MySQL >= 5.7 or MariaDB >= 10.2
- Livewire >= 3.0 (for web dashboard)
License
MIT
Support
For issues, questions, or contributions, please visit the GitHub repository.
Credits
Created by Oluokun Kabiru Adesina