Last active
December 21, 2022 12:57
-
-
Save naagaraa/078ad472b4965576eed7b64c948a7b8b to your computer and use it in GitHub Desktop.
laravel export to separate files .xlsx store at storage. you need install laravel excel for used this command
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 | |
// in controller | |
use App\Exports\WebTrafictExport; | |
use App\Models\Trafict; | |
use Illuminate\Http\Request; | |
use App\Http\Controllers\Controller; | |
class ExportImportController extends Controller | |
{ | |
public function ExportTrafict(Request $request) | |
{ | |
// in controller | |
$trafict = collect(Trafict::whereBetween('updated_at', [$start_date . ' 00:00:00', $end_date . ' 23:59:59']) | |
->orderBy('updated_at') | |
->cursor()); | |
// separete file excel jadi beberapa bagian per 500 row | |
$traficts = []; | |
$count = $trafict->count(); | |
$off_ex = 500; | |
for ($j = 0; $j < $count / $off_ex; $j++) { | |
array_push($traficts, $trafict->skip($j * $off_ex)->take($off_ex)); | |
// if use queue used this | |
(new WebTrafictExport($start_date, $end_date, $traficts[$j]))->queue($filename . "-" . $j . ".xlsx", "webtrafict"); | |
} | |
return back()->withSuccess('Export Done You Can Download Now!'); | |
} | |
} | |
// in class export | |
use Maatwebsite\Excel\Concerns\WithHeadings; | |
use Maatwebsite\Excel\Concerns\FromCollection; | |
use Maatwebsite\Excel\Concerns\WithChunkReading; | |
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; | |
class WebTrafictExport implements WithHeadings, WithStyles, FromCollection, WithChunkReading | |
{ | |
use Exportable; | |
public $queue = 'long-running'; | |
public $timeout = 900; | |
public function __construct(String $start, $end, $data) | |
{ | |
$this->start = $start; | |
$this->end = $end; | |
$this->data = $data; | |
} | |
// chunk data | |
public function chunkSize(): int | |
{ | |
return 500; | |
} | |
// data collection excel | |
public function collection() | |
{ | |
// this looping data or separet file excel | |
return $this->data; | |
} | |
public function map($trafict): array | |
{ | |
return [ | |
$trafict->id, | |
$trafict->title, | |
$trafict->url, | |
$trafict->device, | |
$trafict->ip_client, | |
$trafict->country, | |
$trafict->browser, | |
$trafict->robot, | |
$trafict->platform, | |
$trafict->visitor, | |
$trafict->created_at, | |
$trafict->update_at, | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment