Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

How to make general purpose collection export using Laravel Excel

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.

Install Laravel Excel Package

composer 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

Create CollectionExport collection export class

Create 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.

  • ShouldAutoSize : This interface make column width set automatically based on it’s content
  • WithHeadings : This interface make adding header row

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());
    }
}

Use CollectionExport class in controller

public function export(Request $request)
{
    $data = User::all();

    return Excel::download(new CollectionExport($data), "users.xlsx");
}

Leave a Reply

Your email address will not be published. Required fields are marked *