Skip to content

Instantly share code, notes, and snippets.

@bubba-h57
Last active December 5, 2022 23:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bubba-h57/7bbdc6707ee335c3f72048333ddb4d63 to your computer and use it in GitHub Desktop.
Save bubba-h57/7bbdc6707ee335c3f72048333ddb4d63 to your computer and use it in GitHub Desktop.
Laravel Collection Macro for Reading a CSV file into a Collection
<?php
Collection::macro('getcsv', static function (string $file): Collection {
$resource = fopen($file, 'rb');
$result = new Collection();
$header = fgetcsv($resource);
while (($line = fgetcsv($resource)) !== false) {
$result->add($line);
}
fclose($resource);
return $result;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment