Put an X between the brackets if you have done the following:
Following https://laravel-excel.maatwebsite.nl/docs/3.0/export/basics I am able to export a given model. However, the resulting file has no columns names.
Class:
class InventoriesExport implements FromCollection
{
public function collection()
{
return Inventory::all();
}
}
Controller:
public function getAllProducts()
{
return Excel::download(new InventoriesExport(), 'inventory.xlsx');
}
Expected behavior:
Download an excel file with the inventory contents and the columns names as they are in the related table
Actual behavior:
Download an excel file with the inventory contents without the column names.
I believe I am missing something...
You can close it. I found how to do it:
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use App\Inventory;
class InventoriesExport implements FromQuery, WithHeadings
{
use Exportable;
public function __construct($date, $headings)
{
$this->date = $date;
$this->headings = $headings;
}
public function query()
{
return Inventory::query()
->where('date', $this->date,$this->headings);
}
public function headings() : array
{
return $this->headings;
}
}
Controller:
$headings = [
'id',
'field1',
'field2',
];
$date='2018-06-15 11:54:07';
return (new InventoriesExport($date,$headings))->download($date.'_inventory.xlsx');
I would like to reopen this for an automated version for the headings.
I haven't found any documentation about the order how the fields get exported.
Do they get rendered as columns exactly like in my databases' migration file?
If someone finds this as I found it an hour ago:
I've found an easy solution:
public function headings() : array
{
return $this->collection()->first()->toArray();
}
I will update the official documentation in the next days.
@Lednerb make sense but giving this error;
Call to undefined method stdClass::toArray()
You probably don't need to the toArray then
i had to add array_keys because i have related models loaded in my query/collection
return array_keys($this->collection()->first()->toArray());
Most helpful comment
If someone finds this as I found it an hour ago:
I've found an easy solution:
I will update the official documentation in the next days.