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.


Here is the dump of the Users collection:

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.

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.
Most helpful comment
I did this -
return array_keys($this->model->first()->toArray());Works like a charm.