Skip to content

Instantly share code, notes, and snippets.

@alexweissman
Last active June 10, 2016 00:26
Show Gist options
  • Select an option

  • Save alexweissman/39a0e455e5ced6ba449b5a621ddc2bf4 to your computer and use it in GitHub Desktop.

Select an option

Save alexweissman/39a0e455e5ced6ba449b5a621ddc2bf4 to your computer and use it in GitHub Desktop.
Converting an Eloquent collection to CSV
<?php
use \League\Csv\Writer;
$transform = function($collection) {
$collection->transform(function ($item) {
$item['institution'] = $item['institution']['name'];
$item['status'] = $item['status']['status'];
if ($item['latest_note']){
$item['latest_note_user'] = $item['latest_note']['user']['user_name'];
$item['latest_note'] = $item['latest_note']['note'];
} else {
$item['latest_note_user'] = "";
$item['latest_note'] = "";
}
return $item;
});
return $collection;
});
$collection = $transform($collection);
$csv = Writer::createFromFileObject(new \SplTempFileObject());
$columnNames = array_keys($collection->values()->toArray()[0]);
$csv->insertOne($columnNames);
$collection->each(function ($item) use ($csv) {
error_log(print_r($item->toArray(), true));
// Error here, because $item->toArray() still contains array values
$csv->insertOne($item->toArray());
});
Array
(
[id] => 3
[first_name] => Alex
[last_name] => Weissman
[email] => [email protected]
[institution_id] => 3
[academic_level] => Undergraduate
[courses] => all of them
[taken] => nope
[experience] => dunno
[great] => dunno
[addl] => dunno
[status_id] => 2
[created_at] => 2016-06-06 12:16:40
[updated_at] => 2016-06-07 14:42:55
[activity] => 2016-06-07 14:39:40
[institution] => Array
(
[id] => 3
[name] => University of Maryland College Park
)
[status] => Array
(
[id] => 2
[status] => pending interview
)
[latest_note] => Array
(
[id] => 41
[user_id] => 1
[application_id] => 3
[note] => something boring I guess
[type] => note
[created_at] => 2016-06-07 14:39:40
[updated_at] => 2016-06-07 14:39:40
[user] => Array
(
[id] => 1
[user_name] => root
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment