Skip to content

Instantly share code, notes, and snippets.

@aglipanci
Created March 7, 2022 17:36
Show Gist options
  • Save aglipanci/ec6875bdf755c5e99c901a058a349d04 to your computer and use it in GitHub Desktop.
Save aglipanci/ec6875bdf755c5e99c901a058a349d04 to your computer and use it in GitHub Desktop.
Exportable Collections using maatwebsite/excel
<?php
Collection::macro('export', function (string $filename, array $headers = []) {
return (new class($this, $headers) implements FromCollection, WithHeadings{
use Exportable;
public function __construct(
private \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Collection $collection,
private array $headings = []
) {
}
public function collection()
{
return $this->collection;
}
public function headings(): array
{
return $this->headings;
}
})->download($filename);
});
// Export to Excel
collect($products)->export('products.xlxs');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment