Created
August 29, 2023 12:58
-
-
Save egyjs/a01f0afd4eeaa81437afe2420c6df765 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use App\Exports\ExcelExport; | |
use Illuminate\Database\Eloquent\Builder; | |
use Illuminate\Support\Collection; | |
use Maatwebsite\Excel\Facades\Excel; | |
trait Exportable | |
{ | |
public string $exportExtension = '.xlsx'; | |
public function whenExport(): bool | |
{ | |
if (request()->has('export_excel') && request('export_excel') == "pdf" ){ | |
$this->exportExtension = '.pdf'; | |
} | |
return request('export_excel') ?? false; | |
} | |
public function handleCollectionExport(Collection $collection, array $fields, object $model) | |
{ | |
return Excel::download( | |
new ExcelExport($collection, $fields), | |
$this->getExportFileNameFormat(class_basename($model), NULL), | |
$this->getExportFormat() | |
); | |
} | |
public function handleExport(Builder $queryBuilder, array $fields, string $export_file_name = NULL) | |
{ | |
return Excel::download( | |
new ExcelExport($queryBuilder->get(), $fields), | |
$this->getExportFileNameFormat(class_basename($queryBuilder->getModel()), $export_file_name), | |
$this->getExportFormat() | |
); | |
} | |
protected function getExportFileNameFormat(string $class_basename, ?string $export_file_name): string | |
{ | |
$fileName = $export_file_name ?? $class_basename . 's_' . today()->format('Y-m-d'); | |
$fileName .= $this->exportExtension; | |
return $fileName; | |
} | |
protected function getExportFormat(){ | |
return $this->exportExtension == '.pdf' ? \Maatwebsite\Excel\Excel::DOMPDF : \Maatwebsite\Excel\Excel::XLSX; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment