Skip to content

Instantly share code, notes, and snippets.

@renoirtech
Created January 29, 2019 19:07
Show Gist options
  • Save renoirtech/aaecd41897259d062c3688abe790a182 to your computer and use it in GitHub Desktop.
Save renoirtech/aaecd41897259d062c3688abe790a182 to your computer and use it in GitHub Desktop.
[Laravel] Create a CSV and upload to AWS S3
<?php
use League\Csv\Writer;
use League\Csv\Reader;
use League\Csv\CannotInsertRecord;
use Illuminate\Support\Facades\Storage;
$now = now()->format('U');
$fileName = "file-$now.csv";
$storageInstance = Storage::disk('s3');
$putFileOnStorage = $storageInstance->put($fileName, '');
$fileContent = $storageInstance->get($fileName);
$records = [
[1, 2, 3],
['foo', 'bar', 'baz'],
['john', 'doe', '[email protected]'],
];
try {
$writer = Writer::createFromString($fileContent, 'w');
$writer->insertAll($records);
} catch (CannotInsertRecord $e) {
echo "exception writer";
}
$csvContent = $writer->getContent();
$putFileOnStorage = $storageInstance->put($fileName, $csvContent);
$uploadedFileUrl = $storageInstance->url($fileName);
echo "<a href=\"$uploadedFileUrl\" target=\"_blank\">Download</a>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment