Installation:
composer require chaplean/csv-bundle
Ensure your composer.json includes the package under require.
Bundle Registration:
Add to config/bundles.php (Laravel 5.5+):
return [
// ...
Chaplean\Bundle\CsvBundle\ChapleanCsvBundle::class => ['all' => true],
];
(Note: Adjust namespace if the bundle uses a different one.)
First Use Case: Generate a CSV from a Laravel Eloquent collection:
use Chaplean\Bundle\CsvBundle\CsvExporter;
$users = User::all();
$exporter = new CsvExporter();
$csvContent = $exporter->export($users, ['name', 'email']);
file_put_contents('users.csv', $csvContent);
config/packages/chaplean_csv.yaml (if provided).CsvExporter methods (e.g., export(), setHeaders()).Resources/config/services.xml.Exporting Collections:
$exporter = $this->container->get('chaplean_csv.exporter');
$csv = $exporter->export($collection, ['column1', 'column2']);
setHeaders() to customize column names:
$exporter->setHeaders(['Full Name' => 'name', 'User Email' => 'email']);
Streaming Large Datasets:
$exporter->stream($collection, ['id', 'created_at'])
->setCallback(function ($item) {
return [$item->id, $item->created_at->format('Y-m-d')];
})
->saveTo('large_file.csv');
Custom Mappers:
$exporter->setMapper(new CustomMapper());
class CustomMapper implements MapperInterface {
public function map($item) {
return [$item->formattedAttribute(), $item->value];
}
}
Laravel Service Provider:
Bind the exporter in AppServiceProvider:
$this->app->bind('chaplean_csv.exporter', function () {
return new CsvExporter();
});
API Responses:
return response()->streamDownload(
function () use ($exporter, $data) {
echo $exporter->export($data, ['key']);
},
'export.csv'
);
Queue Jobs:
class ExportCsvJob implements ShouldQueue {
public function handle() {
$exporter = app('chaplean_csv.exporter');
$exporter->export($this->data, $this->columns)
->saveTo(storage_path('app/exports.csv'));
}
}
Namespace Conflicts:
Chaplean\Bundle\CsvBundle; verify autoloading with:
composer dump-autoload
Memory Limits:
$exporter->setChunkSize(1000);
Encoding Issues:
$exporter->setEncoding('UTF-8');
Missing Dependencies:
league/csv is installed (if the bundle relies on it):
composer require league/csv
$exporter->setLogger($this->app->make('logger'));
if (!$exporter->validateHeaders($headers)) {
throw new \InvalidArgumentException('Invalid headers');
}
Custom Writers:
Override CsvWriter to add features (e.g., Excel compatibility):
class ExcelWriter extends CsvWriter {
public function setExcelFormat() { /* ... */ }
}
Event Listeners: Hook into export events (if the bundle supports them):
$exporter->on('export.start', function () {
Log::info('Export initiated');
});
Configuration Overrides:
Extend the bundle’s config in config/packages/chaplean_csv.yaml:
chaplean_csv:
default_encoding: 'UTF-8'
chunk_size: 2000
How can I help you explore Laravel packages today?