MySQL DB Backup

Submitted by CodingwithRK - 8 months ago

If you want to take a SQL file of your MySQL DB, By clicking a button in the Laravel application, then here is the code.

// in web.php
Route::get('backup', function () {
    $backupFileName = 'backup-' . date('Y-m-d-H-i-s') . '.sql';
    $databaseName = env('DB_DATABASE');
    $username = env('DB_USERNAME');
    $password = env('DB_PASSWORD');

    $tables = DB::select('SHOW TABLES');
    $tableNames = array_map('current', $tables);
    $tableNames = implode(' ', $tableNames);

    $command = "mysqldump --user={$username} --password={$password} --skip-lock-tables --no-tablespaces {$databaseName} {$tableNames} > database/backups/{$backupFileName}";
    exec($command);

    return Response::download("database/backups/{$backupFileName}")->deleteFileAfterSend(true);
})->name('db_backup');