Home > Software design >  Laravel Excel: How to set the headers from database fields
Laravel Excel: How to set the headers from database fields

Time:07-02

There are tutorials about customizing headers. But now I want to use the header from database table field. I want to make two types for download. If specified, I write codes for each export, like ID, First Name, Last Name, E-Mail, Date .... If not specified, directly use the table field, like id, firstname, lastname, email, created_at..

CodePudding user response:

You set collection in __constructor. Then you can use it in headings method like

array_keys($this->collection[0]->getAttributes()) </b>

to get attributes names.

CodePudding user response:

If I want to export Users.

This command is provided by laravel-excel:

php artisan make:export UserExport --model=User

UserExport.php

<?php

namespace App\Exports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings; //This line needs to add manually

class UsersExport implements FromCollection, WithHeadings
{
    protected $users;

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }

    // Add this function
    public function headings(): array
    {
        $attributes = array_keys($this->collection()->first()->getAttributes());
        return $attributes;
    }
}

And then edit controller and route file. I get the users excel. But one last thing, the columns do not match. This is because user model have tow hidden columns

app\Models\User

protected $hidden = [
    'password',
    'remember_token',
];

My current solution is to comment out this. Maybe headings() can be further improved.

  • Related