Tricks

Add bulk action to table to export selected record as JSON file within a ZIP archive

Jun 18, 2022
David VINCENT
Table builder, Admin panel
Tables\Actions\BulkAction::make('exportAllAsJson')
->label(__('Export All'))
->icon('heroicon-s-download')
->action(function (Collection $records) {
$archive = new \ZipArchive;
$archive->open('file.zip', \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
foreach ($records as $record) {
$name = Str::slug($record->name, '_') . '.json';
$return = $record->attributesToArray();
$content = json_encode($return, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
$archive->addFromString($name, $content);
}
$archive->close();
return response()->download('file.zip');
})
->deselectRecordsAfterCompletion()

No comments yet…