I'm trying to export certain tables in my Laravel project to CSV in order to both back them up and be able to transfer large amounts of data between different instances of the project.
So far, I've got this export
function:
private function _export($filename, $table)
{
array_unshift($table, array_keys($table[0]));
$handle = fopen($filename, 'w+');
foreach ($table as $row) {
fputcsv($handle, $row);
}
fclose($handle);
}
This takes in a filename (for example, stages.csv
) and an array from a table (for example, Stage::all()->toArray()
) and outputs the file.
The project I'm working on has quite a few many-many relationships, each with their own pivot table. What's a good way of getting the rows of the pivot table into an array I can pass to my export
function?