2

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 ?

1 Answer 1

3

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

}
Sign up to request clarification or add additional context in comments.

4 Comments

I try this way, but debugging with logging looks method headings is called at first and collection after that
You can also try beforeExport. I didnt use it but give a try..
To read data twice nto get separately data and headers? Yes that could work.
Maybe you can do like this. Check update. To avoid DRY.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.