How can you include column headers when exporting Eloquent to Excel in Laravel?

Jaquarh picture Jaquarh · Jan 18, 2019 · Viewed 17.8k times · Source

I am trying to allow users to download Excel, using Laravel Excel files with product information. My current web route looks like this:

Route::get('/excel/release', 'ExcelController@create')->name('Create Excel');

My current Export looks like this:

class ProductExport implements FromQuery
{
    use Exportable;

    public function __construct(int $id)
    {
        $this->id = $id;
    }

    public function query()
    {
        return ProductList::query()->where('id', $this->id);
    }
}

My current controller looks like this:

public function create(Request $request) {

    # Only alowed tables
    $alias = [
        'product_list' => ProductExport::class
    ];

    # Ensure request has properties
    if(!$request->has('alias') || !$request->has('id'))
        return Redirect::back()->withErrors(['Please fill in the required fields.'])->withInput();

    # Ensure they can use this
    if(!in_array($request->alias, array_keys($alias)))
        return Redirect::back()->withErrors(['Alias ' . $request->alias . ' is not supported'])->withInput();

    # Download
    return (new ProductExport((int) $request->id))->download('iezon_solutions_' . $request->alias . '_' . $request->id . '.xlsx');
}

When I head over to https://example.com/excel/release?alias=product_list&id=1 this executes correctly and returns an excel file. However, there is no column headers for the rows. The data comes out like so:

1   150 1   3       2019-01-16 16:37:25 2019-01-16 16:37:25     10

However, this should contain column headers like ID, cost etc... How can I include the column headers in this output?

Answer

miken32 picture miken32 · Jan 18, 2019

According to documentation you can change your class to use the WithHeadings interface, and then define the headings function to return an array of column headers:

<?php
namespace App;

use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ProductExport implements FromQuery, WithHeadings
{
    use Exportable;

    public function __construct(int $id)
    {
        $this->id = $id;
    }

    public function query()
    {
        return ProductList::query()->where('id', $this->id);
    }

    public function headings()
    {
        return ["your", "headings", "here"];
    }
}

This works with all export types (FromQuery, FromCollection, etc.)