Skip to content

Instantly share code, notes, and snippets.

@asvae
Created July 10, 2015 11:22
Show Gist options
  • Save asvae/524afebb9dc7aec6e38e to your computer and use it in GitHub Desktop.
Save asvae/524afebb9dc7aec6e38e to your computer and use it in GitHub Desktop.
Laravel database backup migration
class BackupOldTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Postfix every table with '_bck'
$tables = $this->listTables();
foreach ($tables as $table) {
if ($table === 'migrations') {
continue;
}
Schema::rename($table, $table . '_bck');
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Delete tables without postfix, then delete postfixes themselves.
$tables = $this->listTables();
$pattern = '/_bck$/';
foreach ($tables as $table) {
if (! preg_match($pattern, $table)) {
Schema::drop($table);
}
}
foreach ($tables as $table) {
if (preg_match($pattern, $table)) {
$table_new = preg_replace($pattern, '', $table);
Schema::rename($table, $table_new);
}
}
}
/**
* Make array from table names, dispose of prefixes.
*
* @return mixed
*/
public function listTables()
{
$tables = \DB::select('SHOW TABLES');
foreach ($tables as $key => $table) {
$table_tmp = array_shift($table);
$table_tmp = preg_replace('/^brd_/', '', $table_tmp);
// Don't touch migrations.
if ($table_tmp === 'migrations'){
unset($tables[$key]);
} else{
$tables[$key] = $table_tmp;
}
}
return $tables;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment