Reputation: 1182
I wanna make a job in Laravel which will truncate the database and refill it. However, I wanna make sure I have a backup of the table first and I'm not sure how to create a file with all rows from that table from the same job. I tried using a csv file (using LaraCSV)
public function respaldaDevices() {
$model = Device::get();
$csvExport = new \Laracsv\Export();
$campos = ['serial', 'code', 'rotulo', 'model_id',
'location_id', 'fecha_recepcion', 'guia_recepcion', 'fecha_instalacion',
'fecha_reversa', 'guia_reversa', 'pep', 'status_id', 'serial_prev',
'reversa_prev', 'str_id', 'customer_id', 'technician_id', 'provider_id', 'obs'];
$content = $csvExport->build($model,$campos)->getWriter()->getContent();
$date = date('d-m-Y H-i-s');
Storage::disk('public')->put('respaldo-devices-' . $date . '.csv', $content);
}
but I'd rather have the insert statements.
EDIT: What I've tried so far:
Installed Symfony Process and
use Symfony\Component\Process\Process;
$process = new Process(array('mysqldump', sprintf('-u%s', getenv('DB_USERNAME')),'reportes','devices > devices-'.time().'.sql'));
Mysqldump returns an error 6.
EDIT 2:
Made it work with a deprecated option:
$process = new Process(
"mysqldump " . sprintf('-u%s', getenv('DB_USERNAME')) . " ". " " . "reportes " . "devices > storage\app\devices-".time().".sql --no-create-info"
);
$process->run();
I'd like to know how to do the same but using the array.
Upvotes: 0
Views: 959
Reputation: 3835
You could leverage OS-specific tools like mysqldump instead. You can call this using a process.
Example usage of Process:
$process = new Process([
'mysqldump',
sprintf('-u%s', 'my-username'),
sprintf('-p%s', 'my-password'),
'my-database my-table', // 'my-table' can be left out for a backup of the entire database
'--add-drop-database', // optional
]);
$process->run();
if (!$process->isSuccessful()) {
throw new \Exception('Failed to create backup');
}
$date = date('d-m-Y H-i-s');
Storage::disk('public')->put('respaldo-devices-' . $date . '.csv', $process->getOutput());
Upvotes: 3