BaseExporter Documentation
Introduction
The BaseExporter class is a powerful utility designed to simplify and standardize the process of exporting data to Excel files. It leverages the Maatwebsite/Laravel-Excel package to provide a consistent structure for exporting models and collections to Excel, with support for customizing headings, mapping data, and handling large datasets efficiently.
Key Features
Properties
| Property | Type | Description |
|---|---|---|
$collection | array|Collection|null | The data collection to be exported |
$model | Model|null | The model associated with the export |
$requestCols | array|null | Optional columns to include in the export |
$isExample | bool | Flag to indicate if this is an example export |
Constructor
public function __construct(Collection|array $collection, Model $model, ?array $requestCols, bool $isExample = false)
{
$this->collection = $collection;
$this->model = $model;
$this->requestCols = $requestCols;
$this->isExample = $isExample;
}The constructor initializes the exporter with the data collection, model, requested columns, and a flag indicating whether this is an example export.
Methods
collection()
public function collection()This method implements the FromCollection interface and returns the data collection to be exported. It handles three scenarios:
- If the model has an
export()method, it uses that method to get the data - If
$isExampleis true and the model has animportExample()method, it uses that method to get example data - Otherwise, it returns the collection provided in the constructor or the model's fillable attributes for examples
map($row)
public function map($row): arrayThis method implements the WithMapping interface and maps each row of data to an array for export. It:
- Returns an empty array if this is an example export
- Gets the exportable columns from the model (using
exportable()method if available, otherwise usinggetFillable()) - Filters columns based on
$requestColsif provided - Handles dot notation for accessing nested relation properties
- Maps each column to its corresponding value in the row
headings()
public function headings(): arrayThis method implements the WithHeadings interface and returns the column headings for the export. It:
- Gets the exportable columns from the model (using
exportable()method if available, otherwise usinggetFillable()) - Filters columns based on
$requestColsif provided - Formats the column names by replacing dots, dashes, and underscores with spaces and title-casing the result
chunkSize()
public function chunkSize(): intThis method implements the WithCustomChunkSize interface and returns the chunk size for processing large datasets. It returns a default value of 500, which helps optimize memory usage when exporting large amounts of data.
How to Use BaseExporter
The BaseExporter class is primarily used through the export() and getImportExample() methods in the BaseRepository class. These methods handle the creation of the exporter and the downloading of the Excel file.
Exporting Data
To export data to an Excel file, you can use the export() method in a repository that extends BaseRepository:
// In a controller
public function export(Request $request)
{
$ids = $request->ids ?? [];
return $this->categoryService->export($ids);
}
// In a service
public function export(array $ids = []): BinaryFileResponse
{
return $this->repository->export($ids);
}
// In BaseRepository
public function export(array $ids = []): BinaryFileResponse
{
if (!count($ids)) {
$collection = $this->globalQuery()->get();
} else {
$collection = $this->globalQuery()->whereIn('id', $ids)->get();
}
$requestedColumns = request('columns') ?? null;
return Excel::download(
new BaseExporter($collection, $this->model, $requestedColumns),
$this->model->getTable().'.xlsx',
);
}Generating Import Examples
To generate an example Excel file for importing data, you can use the getImportExample() method:
// In a controller
public function getImportExample()
{
return $this->categoryService->getImportExample();
}
// In a service
public function getImportExample(): BinaryFileResponse
{
return $this->repository->getImportExample();
}
// In BaseRepository
public function getImportExample(): BinaryFileResponse
{
return Excel::download(
new BaseExporter(collect(), $this->model, null, true),
$this->model->getTable().'-example.xlsx'
);
}Customizing Exports in Models
You can customize how a model is exported by implementing specific methods in your model class:
exportable()
Define which columns should be included in the export:
public function exportable(): array
{
return [
'name',
'email',
'created_at',
'user.name', // Nested relation
];
}export()
Provide a custom collection for export:
public function export(): Collection
{
return $this->with('user')->get();
}importExample()
Provide example data for the import template:
public function importExample(): Collection
{
return collect([
[
'name' => 'Example Name',
'email' => 'example@example.com',
]
]);
}