-
-
Save oliuz/be504e371e023c7747f5073a4d4511b4 to your computer and use it in GitHub Desktop.
Exporting CSV Reports with Renderless Livewire Component
This file contains hidden or 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\Http\Livewire; | |
use Livewire\Component; | |
use Livewire\Attributes\Renderless; | |
use App\Traits\HasFilteredReports; | |
class Reports extends Component | |
{ | |
use HasFilteredReports; | |
#[Renderless] | |
public function exportCsv() | |
{ | |
// liveiwre 2 (works with livewire 3 too) | |
// $this->skipRender(); | |
return response()->stream(function () { | |
// Open a writable stream to php://output (the browser) | |
$file = fopen('php://output', 'w'); | |
// Write the header row to the CSV | |
fputcsv($file, $this->selectedColumns); | |
$this->getFilteredReports()->each(function ($row) use ($file) { | |
// Parse the row data and write it to the CSV | |
fputcsv($file, $row->toArray()); | |
}); | |
// Close the CSV file | |
fclose($file); | |
}, 200, [ | |
"Content-type" => "text/csv", | |
"Content-Disposition" => "attachment; filename=reports.csv", | |
"Pragma" => "no-cache", | |
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0", | |
"Expires" => "0" | |
]); | |
} | |
public function render() | |
{ | |
// some database operations which needed to render the component | |
// operations happening here will not be executed if you call nonRenderingMethod() | |
return view('livewire.reports',[ | |
'reports'=> $this->getFilteredReports(), | |
// other variables | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment