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

Dezaka's avatar

Laravel Excel export table with relationship

Hi, so i tried to export a table with a one to many relationship with a date range and a column filter input by the user the date range is for the table 1 and the column filter is for table 2

so to do that i tried to make query like this

public function collection()
    {
        return Pengaduan::with('PengaduanInven')
            ->whereHas('PengaduanInven', function ($query) {
                $query->where('inventaris', $this->inventarisFilter);
            })
            ->where('status_perbaikan', "1")
            ->whereBetween('tanggal_pengaduan', [$this->startDate, $this->endDate])
            ->get(['tanggal_pengaduan', 'id_ruangan', 'tanggal_selesai', 'keterangan_selesai']);

    }

and then withMapping

public function map($pengaduan): array
    {
        return [
            $pengaduan->tanggal_pengaduan,
            $pengaduan->id_ruangan,
            $pengaduan->PengaduanInven->implode('inventaris', ', '),
            $pengaduan->PengaduanInven->implode('jumlah', ', '), 
            $pengaduan->tanggal_selesai,
            $pengaduan->keterangan_selesai,
        ];
    }

so the thing is this code did export an Excel file but the exported data is only 'tanggal_pengaduan','id_ruangan','tanggal_selesai',and 'keterangan_selesai' the other two didnt got exported, am i doing somthing wrong? in the query or somewhere ? please help and im sorry if this code looks bad im new to laravel :) btw this is my controller and my model

 public function export(Request $request){
        $startDate = $request->input('date_start');
        $endDate = $request->input('date_end');
        $inventarisFilter = $request->input('inventaris');
     
        return Excel::download(new PengaduanExport($startDate, $endDate, $inventarisFilter), 'pengaduan.xlsx');
    }
  public function PengaduanInven(){
        return $this->hasMany(PengaduanInven::class, 'nomor_pengaduan','nomor_pengaduan');
    }```
0 likes
1 reply
s4muel's avatar

how does your PengaduanExport class look like? didnt you forget to extend/implement the WithMapping?

use Maatwebsite\Excel\Concerns\WithMapping; //or your library

class PengaduanExport implements FromQuery, WithMapping //<- here
{    
    public function map($pengaduan): array
    {
        //...
    }
}

Please or to participate in this conversation.