How can you include column headers when exporting Eloquent to Excel in Laravel?
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use DB;
class LocationTypeExport implements FromCollection,WithHeadings
{
public function collection()
{
$type = DB::table('location_type')->select('id','name')->get();
return $type ;
}
public function headings(): array
{
return [
'id',
'name',
];
}
}
<?php
namespace App\Exports;
use App\Models\UserDetails;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
class CustomerExport implements FromCollection, WithHeadings
{
public function collection()
{
return UserDetails::whereNull('business_name')
->select('first_name','last_name','mobile_number','dob','gender')
->get();
}
public function headings() :array
{
return ["First Name", "Last Name", "Mobile","DOB", "Gender"];
}
}
You can combine this with array_keys
to dynamically get your column headers:
use Maatwebsite\Excel\Concerns\FromCollection;
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(): array
{
return array_keys($this->query()->first()->toArray());
}
}
If you're using it with a collection, you can do so like the following:
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ProductExport implements FromCollection, WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
// for selecting specific fields
//return ProductList::select('id', 'product_name', 'product_price')->get();
// for selecting all fields
return ProductList::all();
}
public function headings(): array
{
return $this->collection()->first()->keys()->toArray();
}
}
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(): array
{
return ["your", "headings", "here"];
}
}
This works with all export types (FromQuery
, FromCollection
, etc.)