Created
February 20, 2022 02:14
-
-
Save edgrosvenor/a326ce974c3c710f68258fd0b3877b28 to your computer and use it in GitHub Desktop.
Zero effort export to csv for Eloquent models
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Support\Str; | |
use ReflectionClass; | |
trait Exportable | |
{ | |
protected ?array $exportRows = null; | |
protected array $exportTypes = ["bigint", "boolean", "date", "datetime", "decimal", "float", "guid", "integer", | |
"smallint", "string"]; | |
public function toCsv() | |
{ | |
$file = fopen(storage_path($this->getCsvFilename()), 'wb'); | |
fputcsv($file, $this->getExportKeys()); | |
$this->getExportQuery()->get()->each(fn($record) => fputcsv($file, $record->toArray())); | |
fclose($file); | |
} | |
public function getExportQuery() | |
{ | |
return static::query()->without($this->with)->select($this->getExportKeys()); | |
} | |
public function getExportKeys(): array | |
{ | |
if ($this->exportRows !== null) { | |
return $this->exportRows; | |
} | |
$keys = []; | |
foreach (array_keys(static::without($this->with)->first()->toArray()) as $col) { | |
if (in_array(DB::getSchemaBuilder()->getColumnType($this->getTable(), $col), $this->exportTypes)) { | |
$keys[] = $col; | |
} | |
} | |
return $keys; | |
} | |
public function getCsvFilename(): string | |
{ | |
return Str::plural((new ReflectionClass($this))->getShortName()) . ' ' . now()->format('Y-m-d') . '.csv'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment