Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Simple Developer
Simple Developer
How to make general purpose collection export using Laravel Excel
Making all export class for each collection export is pain to work. Lets make a general purpose collection export using Laravel Excel
package.
Laravel Excel
Packagecomposer require maatwebsite/excel
If composer require fails on Laravel 9 because of the simple-cache
dependency, you will have to specify the psr/simple-cache
version as ^2.0
in your composer.json to satisfy the PhpSpreadsheet dependency. You can install both at the same time as:
composer require psr/simple-cache:^2.0 maatwebsite/excel
CollectionExport
collection export classCreate CollectionExport
class using php artisan command
php artisan make:export CollectionExport
Open App\Exports\CollectionExport.php
file and add ShouldAutoSize
and WithHeadings
interface to make result file more readable.
And implement code like below:
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
class CollectionExport implements FromCollection, ShouldAutoSize, WithHeadings
{
protected $source;
public function __construct($source)
{
$this->source = $source;
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return $this->source;
}
public function headings(): array
{
// Use collection key to set header
return array_keys($this->source->first()->toArray());
}
}
CollectionExport
class in controllerpublic function export(Request $request)
{
$data = User::all();
return Excel::download(new CollectionExport($data), "users.xlsx");
}