Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

Laravel Excel : how to export only some columns ?

Hello :

I would like to export only some columns (email) :

the column email does not exists in table , but it's an accessor !(impossible to say ->get(["email"]))

Resources controller

 return Excel::download(new CompaniesExport($request->segmentId),'file_name.xls');

CompaniesExport :

 public function collection()
    {

        $this->sorting = 'id';
        $this->sortOrder = 'asc';

        if ($this->segmentId == 0) {
            $searchableTable = SearchableTable::where('name', 'like', 'teamleader_companies')->first();
            return TeamleaderCompany::orderBy($this->sorting, $this->sortOrder)->get();
        }
        (...)
    }
0 likes
9 replies
GodziLaravel's avatar

@sti3bas

It exists in my model :

protected $appends=['tags','email','telephone','deals'];
(...)    
public function getEmailAttribute()
    {
        $this->loadMissing('teamleaderCompanyEmails');
       return $this->teamleaderCompanyEmails->where('type','=','primary')->implode('email',',');
    }

In my controller when I:

return TeamleaderCompany::get(['email']);

it returns :

Undefined column: 7 ERROR: column "email" does not exist LINE 1: select "email" from "teamleader_companies" ^ (SQL: select "email" from "teamleader_companies")
GodziLaravel's avatar

Note :

When I return TeamleaderCompany::get(); I can see the email attribute

Sti3bas's avatar

@mostafalaravel If you only need to export an email, you can try this:

return TeamleaderCompany::orderBy($this->sorting, $this->sortOrder)->get()->pluck('email');
alabamustapha's avatar

'flatMap' did not work well for me, I used 'map' instead. so you have something like

return TeamleaderCompany::orderBy($this->sorting, $this->sortOrder)->get()->map(function($leader) {
   return [
      'email' => $leader->email,
      'other_column' => $leader->something,
   ];
});

So for example to get the name and phone_number column for a User you will have

return User::all()->map(function($user) {
            return [
               'name' => $user->name,
               'phone_number' => $user->phone_number,
            ];
         });
rawilk's avatar

If you add the interfaces Maatwebsite\Excel\Concerns\WithHeadings and Maatwebsite\Excel\Concerns\WithMapping to your export class, you can do this a lot easier IMO.

In your export class, you will then just need to add the methods that are required by each interface:

public function headings(): array
{
    return ['email']; // add any other columns needed
}

public function map($row): array
{
    // $row will be a single model instance passed in to here
    return [$row->email]; // add the data from the columns defined in "headings()"
}

Please or to participate in this conversation.