Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Last active November 27, 2023 08:35
Show Gist options
  • Save MrPunyapal/68d0ecd534f1f097e17833866a32173d to your computer and use it in GitHub Desktop.
Save MrPunyapal/68d0ecd534f1f097e17833866a32173d to your computer and use it in GitHub Desktop.
Exporting CSV Reports with Renderless Livewire Component
<?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