Courses

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

Previous: Products Delete and Multi-Delete
avatar

Hey Povilas, I try to export with every method but data need to be selected. if not selected the export file is empy. How to export all data withoud be selected? Can you add a button to select everthing on the page? Can you show production quantity? For example I want to click a button/select to show 100 or 50 or 1000 products. At least can you create that as components on livewire kit?

avatar

A few ideas for the future, thanks. For now I'm waiting for Livewire 3 and then will create more content about Livewire, and refresh the old ones.

avatar

Can you add dark mode switcher, infinity loading on livewire kit? On bulk delete add the select all checkbox. Its great features. I start using the livewire and the livewire kit is very helpful. I love livewire kit and I wait the new version with livewire 3.

avatar

We'll see about new components for Livewire Kit when Livewire 3 is released, thanks for the ideas.

avatar

@prpanto dark mode switcher shouldn't be made with Livewire. You should use Alpine.js for that.

avatar

Hello, I don't know if it is the best solution, but to export all without select any register I did this

if(!empty($this->productIDs))
return Product::with('categories', 'country')->find($this->productIDs);

return Product::with('categories', 'country')->get();

And it's worked like a charm!

avatar
You can use Markdown
avatar

Hello,

Should the command : php artisan make:export ProductsExport --model=Product

Create the complete ProductsExport as in your tutorial. Because in my case I only have :

class ProductsExport implements FromCollection { /** * @return \Illuminate\Support\Collection */ public function collection() { return Product::all(); } }

avatar

No, the command itself doesn't write the full code for you, you have to write it yourself.

avatar

When I run php artisan make:export ProductsExport --model=Product I am getting a error

ERROR Command "make:export" is not defined. Did you mean one of these?

⇂ make:cast
⇂ make:channel ⇂ make:command ⇂ make:component ⇂ make:controller ⇂ make:event ⇂ make:exception ⇂ make:factory ⇂ make:job ⇂ make:request ⇂ make:resource ⇂ make:rule ⇂ make:scope ⇂ make:seeder ⇂ make:test I am running PhpStorm 2023.1, Laravel 10.9.0, breeze 1.20.2, Livewire 2.12.3 and maatwebsite/excel 1.1.5 ran composer update and I got Nothing to install, update or remove. WHAT am I missing why am I getting this ERROR ???

Ps. I did run your composer require maatwebsite/excel dompdf/dompdf First then php artisan make:export ProductsExport --model=Product

avatar
You can use Markdown
avatar

When running: composer require maatwebsite/excel dompdf/dompdf

I got all kind of errors in the output:

Package phpoffice/phpexcel is abandoned, you should avoid using it. Use phpoffice/phpspreadsheet instead.

Class PHPExcel_Properties located in D:/PROJECTS/LEARNING/LARAVEL/order-management-system/vendor/phpoffice/phpexcel/Classes\PHPExcel\Chart\Properties.php does not comply with psr-0 autoloading standard. Skipping. Class PHPExcel_Best_Fit located in D:/PROJECTS/LEARNING/LARAVEL/order-management-system/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\bestFitClass.php does not comply with psr-0 autoloading standard. Skipping. Class PHPExcel_Exponential_Best_Fit located in D:/PROJECTS/LEARNING/LARAVEL/order-management-system/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\exponentialBestFitClass.php does not comply with psr-0 autoloading standard. Skipping. Class PHPExcel_Linear_Best_Fit located in D:/PROJECTS/LEARNING/LARAVEL/order-management-system/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\linearBestFitClass.php does not comply with psr-0 autoloading standard. Skipping. Class PHPExcel_Logarithmic_Best_Fit located in D:/PROJECTS/LEARNING/LARAVEL/order-management-system/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\logarithmicBestFitClass.php does not comply with psr-0 autoloading standard. Skipping. Class PHPExcel_Polynomial_Best_Fit located in D:/PROJECTS/LEARNING/LARAVEL/order-management-system/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\polynomialBestFitClass.php does not comply with psr-0 autoloading standard. Skipping. Class PHPExcel_Power_Best_Fit located in D:/PROJECTS/LEARNING/LARAVEL/order-management-system/vendor/phpoffice/phpexcel/Classes\PHPExcel\Shared\trend\powerBestFitClass.php does not comply with psr-0 autoloading standard. Skipping. Class Database\Factories\CategoryFactory located in D:/PROJECTS/LEARNING/LARAVEL/order-management-system/database/factories\ProductFactory.php does not comply with psr-4 autoloading standard. Skipping.

Also php artisan make:export ProductsExport --model=Product didn't work at all:

ERROR Command "make:export" is not defined. Did you mean one of these? with list here...

This part of the class doesn't work for me at all using Laravel 10 on windows 10

avatar

It seems that something is wrong with the package maybe. Somehow it tries to install wrong version. To fix it now manually add "maatwebsite/excel": "^3.1" to the composer.json and run composer update.

avatar

Hi RangeCoder did you solve that ?

avatar

Look like I did Syed, I had to uncomment extension=zip in my PHP.ini settings file

After doing what Nerijus suggested I got this error (THANK YOU Nerijus!):

Your requirements could not be resolved to an installable set of packages.

With a wall of text after it but it had one useful thing in the end...

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

So after that I typed: composer update --with-all-dependencies and got this error:

Your requirements could not be resolved to an installable set of packages.

Problem 1 > - maatwebsite/excel[3.1.28, ..., 3.1.30] require phpoffice/phpspreadsheet 1.16.* -> satisfiable by phpoffice/phpspreadsheet[1.16.0]. > - maatwebsite/excel[3.1.31, ..., 3.1.48] require phpoffice/phpspreadsheet ^1.18 -> satisfiable by phpoffice/phpspreadsheet[1.18.0, ..., 1.28.0]. > - maatwebsite/excel 3.1.27 requires phpoffice/phpspreadsheet ^1.16 -> satisfiable by phpoffice/phpspreadsheet[1.16.0, ..., 1.28.0]. > - maatwebsite/excel 3.1.26 requires phpoffice/phpspreadsheet ^1.15 -> satisfiable by phpoffice/phpspreadsheet[1.15.0, ..., 1.28.0]. > - maatwebsite/excel[3.1.0, ..., 3.1.25] require php ^7.0 -> your php version (8.2.4) does not satisfy that requirement. > - phpoffice/phpspreadsheet[1.15.0, ..., 1.28.0] require ext-zip * -> it is missing from your system. Install or enable PHP's zip extension. > - Root composer.json requires maatwebsite/excel ^3.1 -> satisfiable by maatwebsite/excel[3.1.0, ..., 3.1.48].

To enable extensions, verify that they are enabled in your .ini files: > - D:\xampp\php\php.ini You can also run php --ini in a terminal to see which files are used by PHP in CLI mode. Alternatively, you can run Composer with --ignore-platform-req=ext-zip to temporarily ignore these required extensions.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

That was much more useful like I pointed at that ext-zip was requered. So enabled that ext in the php settings and retyping that command it worked!

Also php artisan make:export ProductsExport --model=Product did work after!

avatar

It's something with that excel package that it won't install the correct version. I think it would be best if you would raise a issue to the author.

avatar

If you have problems installing, you can try this way

composer require maatwebsite/excel
avatar
You can use Markdown
avatar

When I run

php artisan make:export ProductsExport --model=Product

I am getting a error

ERROR Command "make:export" is not defined. Did you mean one of these?

⇂ make:cast ⇂ make:channel ⇂ make:command ⇂ make:component ⇂ make:controller ⇂ make:event ⇂ make:exception ⇂ make:factory ⇂ make:job ⇂ make:request ⇂ make:resource ⇂ make:rule ⇂ make:scope ⇂ make:seeder ⇂ make:test

I am running PhpStorm 2023.1, Laravel 10.9.0, breeze 1.20.2, Livewire 2.12.3 and maatwebsite/excel 1.1.5 with psr/simple-cache 1.0.0 ran composer update and I got Nothing to install, update or remove. WHAT am I missing why am I getting this ERROR ???

Ps. I did run your composer require maatwebsite/excel dompdf/dompdf First then php artisan make:export ProductsExport --model=Product

avatar
Luis Antonio Parrado

composer require maatwebsite/excel installs by default the version 1.0 and its outdated. You need install a version ^3.1. Therefore you must run the command

composer require maatwebsite/excel "^3.1"
avatar
You can use Markdown
avatar

Hears is what worked for me

First in the Php ini file enable gd and zip to make this work. Nest install composer require phpoffice/phpspreadsheet -W Then composer require maatwebsite/excel dompdf/dompdf Next php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config And Finaly php artisan make:export ProductsExport --model=Product CSV XLSX AND PDF all worked just fine for me.

avatar
You can use Markdown
avatar

The last step of this part of the tutorial showing how to add the export() method in the ProductsList component shows this use statement;

use Symfony\Component\HttpFoundation\BinaryFileResponse;

I had to also use the following classes to get the file exports to work;

use App\Exports\ProductsExport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Response;
avatar

For the response namespace I believe it should be from symfony.

use Symfony\Component\HttpFoundation\Response;
avatar

Ah, thanks - believe it or not I'd done the whole course up to this point without realising there was a repo for it on Github. D'oh. I think I realised in the next lesson. You are spot on.

avatar
You can use Markdown
avatar
You can use Markdown