Back to Course |
Practical Livewire 3: Order Management System Step-by-Step

Products Export to XLS / CSV / PDF

In this lesson, we will use Laravel Excel package to export selected products into CSV, XLSX, and PDF.

Let's start by adding three buttons, which will trigger the export() method in the Livewire component.

resources/views/livewire/products-list.blade.php:

<div class="mb-4">
<div class="mb-4">
<a class="inline-flex items-center px-4 py-2 text-xs font-semibold tracking-widest text-white uppercase bg-gray-800 rounded-md border border-transparent hover:bg-gray-700">
Create Product
</a>
</div>
 
<button type="button"
wire:click="deleteConfirm('deleteSelected')"
wire:loading.attr="disabled"
@disabled(! $this->selectedCount)
class="px-4 py-2 mr-5 text-xs text-red-500 uppercase bg-red-200 rounded-md border border-transparent hover:text-red-700 hover:bg-red-300 disabled:opacity-50 disabled:cursor-not-allowed">
Delete Selected
</button>
 
<x-primary-button wire:click="export('csv')">CSV</x-primary-button>
<x-primary-button wire:click="export('xlsx')">XLSX</x-primary-button>
<x-primary-button wire:click="export('pdf')">PDF</x-primary-button>
</div>

products export buttons

Next, we need to install the Laravel Excel package and create Export.

composer require maatwebsite/excel dompdf/dompdf
php artisan make:export ProductsExport --model=Product

Dompdf is needed for exporting to PDF.

Now what everything means inside ProductExport you can read in the official documentation.

app/Exports/ProductsExport.php:

use App\Models\Product;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
 
class ProductsExport implements FromCollection, WithHeadings, WithMapping
{
public function __construct(private array $productIDs) {}
 
public function headings(): array
{
return [
'Name',
'Categories',
'Country',
'Price'
];
}
 
public function map($product): array
{
return [
$product->name,
$product->categories->pluck('name')->implode(', '),
$product->country->name,
'$' . number_format($product->price, 2)
];
}
 
public function collection(): Collection
{
return Product::with('categories', 'country')->find($this->productIDs);
}
}

All that's left is to implement the export() method in the LIvewire Component.

app/Livewire/ProductsList.php:

use App\Exports\ProductsExport;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
 
class ProductsList extends Component
{
// ...
 
public function export(string $format): BinaryFileResponse
{
abort_if(! in_array($format, ['csv', 'xlsx', 'pdf']), Response::HTTP_NOT_FOUND);
 
return Excel::download(new ProductsExport($this->selected), 'products.' . $format);
}
 
// ...
}

Now, after selecting some products and clicking one of the buttons to export, you will get exported file.

excel export