Search code examples
laravellaravel-5maatwebsite-excel

Generating csv file with Maatwebsite/Laravel-Excel how make headings returns dynamic array


In laravel 5.8 generating csv file I use https://github.com/Maatwebsite/Laravel-Excel plugin and it works ok, but as I use headings method for header generating https://docs.laravel-excel.com/3.1/exports/mapping.html

I need to have headers depending on result set I got from the db :

<?php

namespace App\Exports;

use Auth;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class exportSearchResults implements FromCollection, WithHeadings
{
    public function collection()
    {
        $searchResultRows = SearchResult
            ::getByUserList($this->user_list_id)
            ->select( 'source_id' )
            ->groupBy( 'source_id' )
            ->orderBy('source_id', 'asc')
            ->get()
            ->toArray();
            ...
        return $searchResultRows;
    }

    public function headings(): array
    {
        return [
            'field',
            'value',
        ];
        // I need Somehow to return content of this array based on $searchResultRows array in collection method
    }

}

Is there is such way ?


Solution

  • You can use something like this:

    <?php
    
    namespace App\Exports;
    
    use Auth;
    use Maatwebsite\Excel\Concerns\FromCollection;
    use Maatwebsite\Excel\Concerns\WithHeadings;
    
    class exportSearchResults implements FromCollection, WithHeadings
    {
        private $searchResultRows;
    
        public function collection()
        {
            return $this->searchResultRows;
        }
    
    
        public function headings(): array {
             $this->searchResultRows = SearchResult::getByUserList($this->user_list_id)
                ->select( 'source_id' )
                ->groupBy( 'source_id' )
                ->orderBy('source_id', 'asc')
                ->get()
                ->toArray();
                ...
            if ($this->searchResultRows ...){
            return [
                'field',
                'value',
            ];
            } else {
              return ...
            }
        }
    
    }