Laravel-excel: [Question] Column heading is not printed for Collection

Created on 3 May 2018  路  5Comments  路  Source: Maatwebsite/Laravel-Excel

Prerequisites

  • [ x] Able to reproduce the behaviour outside of your code, the problem is isolated to Laravel Excel.
  • [ x] Checked that your issue isn't already filed.
  • [ x] Checked if no PR was submitted that fixes this problem.

Versions

  • PHP version: 7.2.3-1
  • Laravel version: 5.6.20
  • Package version: 3.0

Description

I am trying to create a 'xlsx' document of users from the 'Users' table with auto generated column headings. I referred to the question here and created the following code:

class UsersExports implements FromCollection, Responsable, WithHeadings
{
    use Exportable;

    private $fileName = 'users.xls';

    public function headings(): array
    {
        return $this->collection()->first()->keys();
    }

    public function collection()
    {
        return User::all();
    }
}

But this is throwing an error Method Illuminate\Database\Query\Builder::keys does not exist. I can create the mappings and headings as mentioned here but for this specific task, I need to just autogenerate the column headings and I am not too bothered about performance hit.

Steps to Reproduce

Current Output

output

Expected Output

expected

Additional Information

Here is the dump of the Users collection:
collection

Most helpful comment

I did this -
return array_keys($this->model->first()->toArray());
Works like a charm.

All 5 comments

Typo on my side in the comment, should be: $this->collection()->keys()

@patrickbrouwers I did that and got another error headings() must be of the type array, object returned. So I did the following but that just outputs the spreadsheet without the headings as before.

return $this->collection()->keys()->toArray();.

Try dd($keys) instead the headings method, perhaps you'll find out why.

Alternatively (and in my opinion the best solution) is to provide the heading manually. Calling $this->collection()->keys will requery your database, which will have a big drain on performance.

I did a dump of the $this->collection()->keys()->toArray(); and it simply returned an array of collection keys as follows which makes sense. Apologies for not checking this early.

keys

You are right that it is better to provide headings manually and after some thinking around, decided to go for that option with a workaround on the business process. Thanks for the help

I did this -
return array_keys($this->model->first()->toArray());
Works like a charm.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bahmanyaghoobi picture bahmanyaghoobi  路  3Comments

ellej16 picture ellej16  路  3Comments

lucatamtam picture lucatamtam  路  3Comments

kurianic picture kurianic  路  3Comments

amine8ghandi8amine picture amine8ghandi8amine  路  3Comments