close

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

Hello Guys, How are you all? Hope You all Are Fine. Today we are talking about How can you include column headers when exporting Eloquent to Excel in Laravel? in php. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

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

Today we are talking about How can you include column headers when exporting Eloquent to Excel in Laravel? in php.

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

  1. How To Solve can you include column headers when exporting Eloquent to Excel in Laravel Error ?

    To Solve can you include column headers when exporting Eloquent to Excel in Laravel Error 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:

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

    To Solve can you include column headers when exporting Eloquent to Excel in Laravel Error 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:

Solution 1

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 (FromQueryFromCollection, etc.)

Solution 2

<?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',
        ];
    }
}

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment