Skip to content

Instantly share code, notes, and snippets.

@singhofmarco
Created March 6, 2020 17:04
Show Gist options
  • Save singhofmarco/ae1e032d34c7c8f24afb4bc57290cda6 to your computer and use it in GitHub Desktop.
Save singhofmarco/ae1e032d34c7c8f24afb4bc57290cda6 to your computer and use it in GitHub Desktop.
Lazy export of DataTable
<?php
namespace App\DataTables;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Services\DataTable;
class BaseDataTable extends DataTable
{
protected $exportClass = LazyDataTablesExportHandler::class;
protected function buildExcelFile()
{
$source = app()->call([$this, 'query']);
$source = $this->applyScopes($source);
$dataTable = app()->call([$this, 'dataTable'], compact('source'));
$dataTable->skipPaging();
$query = $dataTable->getFilteredQuery();
$dataForExport = $query->cursor();
return new $this->exportClass($dataForExport);
}
}
<?php
namespace App\DataTables;
use Illuminate\Support\LazyCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class LazyDataTablesExportHandler implements FromCollection, WithHeadings
{
use Exportable;
/**
* @var LazyCollection
*/
protected $collection;
/**
* LazyDataTablesExportHandler constructor.
*
* @param LazyCollection $collection
*/
public function __construct(LazyCollection $collection)
{
$this->collection = $collection;
}
/**
* @return LazyCollection
*/
public function collection()
{
return $this->collection;
}
/**
* @return array
*/
public function headings(): array
{
$first = $this->collection->first();
if ($first) {
return array_keys($first->toArray());
}
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment