I'm not sure to understand what you need. Is it a query problem ? an export problem ? something else ?
Flatten Eloquent Query results for CSV export
I want to flatten an eloquent query result which includes a number of many to many relationships using pivot tables. So all the returned data is in a single dimension, with the for export to CSV (using maatwebsite/excel).
Here's what I have in the Export class:
<?php
namespace App\Exports;
use App\Models\Chit;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ChitsExport implements FromCollection, WithHeadings {
private $shootId;
public function setShootId($shootId) {
$this->shootId = $shootId;
}
public function collection() {
if ($this->shootId) {
return Chit::with('Negotiables', 'faaSupplementaryCharges', 'pactSupplementaryCharges')
->where('shoot_id', $this->shootId)->get();
}
return null;
}
public function headings(): array {
return array_keys($this->collection()->first()->toArray());
}
}
I want the output format to be something like:
ID, Name,NegotableName1,NegotiableName2,SupplementaryCharge1....
Where the column names for the Negotiables & Supplementary charges would be the aggregated from the join tables with the values of each of those fields shown in the sheet.
So a simple example might be:
Name,Change Of Clothes,Working With Animals
Fred,20,40
Joe,,40
Melissa,20,40
Catherine,20,
"Change of clothes" & "Working with animals" would be the 'Name' column value from the 'Negotiables' table and the values would be the corresponding 'Amount' field in the Negotiables table.
I can't for the life of me work out how to do this, any ideas?
Please or to participate in this conversation.