I'm trying to create an Excel but it won't download correctly or at all. This is my full code from the front, in the vue method I originally was going to use Inertia to make the request but had the same problem so I tried $http instead but no luck, I'm not sure if that makes a difference.
Request from frontend using Vue
export_excel(val) {
this.$http.post(`/surveys/surveys/${this.$page.props.survey.id}/excel_report`, {
filters: this.filters
});
},
Routes
Route::prefix('surveys')->group(function () {
Route::post('/{id}/excel_report', [SurveyController::class, 'get_excel_report']);
});
Controller
public function get_excel_report(Request $request, $id)
{
$survey = Survey::findOrFail($id);
$result = SurveyReportDetail::with(
'question',
'section',
'report.user',
'report.survey.sections.questions',
'report.sale_point.format.chain.channel'
);
if ($request->get('filters.images')) {
$result->whereHas('report.survey.sections.questions', function ($query) {
$query->where('response_type', '!=', 'image');
});
}
$result->whereHas('report', function ($query) use ($request, $id) {
//sale_point filter removed for length
if (!empty($request->get('init_date'))) {
$query->where('date', '>=', $request->get('init_date'));
}
if (!empty($request->get('end_date'))) {
$query->where('date', '<=', $request->get('end_date'));
}
//supervisor filter removed for length
});
return (new SurveyReportGeneralExport($result->get()->toArray()))->download('test.xlsx');
}
And Finally the Export File
class SurveyReportGeneralExport implements FromArray, WithHeadings
{
use Exportable;
protected $items;
public function __construct(array $items)
{
$this->items = $items;
}
public function array(): array
{
$data = [];
foreach ($this->items as $item) {
$data[] = [
$item['report']['date'],
$item['report']['latitude'],
$item['report']['longitude'],
!empty($item['report']['sale_point']['format']['chain']['channel']['description']) ?
$item['report']['sale_point']['format']['chain']['channel']['description'] : '',
!empty($item['report']['sale_point']['format']['chain']['description']) ?
$item['report']['sale_point']['format']['chain']['description'] : '',
!empty($item['report']['sale_point']['format']['description']) ?
$item['report']['sale_point']['format']['description'] : '',
!empty($item['report']['sale_point']['name']) ?
$item['report']['sale_point']['name'] : '',
$item['report']['user']['name'],
$item['section']['description'],
$item['question']['description']
];
}
return $data;
}
public function headings(): array
{
$headings = [
'FECHA',
'LATITUD',
'LONGITUD',
'CANAL',
'CADENA',
'FORMATO',
'PUNTO DE VENTA',
'USUARIO',
'SECCION',
'PREGUNTA',
'RESPUESTA'
];
if (Survey::findOrFail($this->items[0]['report']['survey']['id'])->pluck('is_evaluation')) {
$headings[] = 'NOTA';
}
return $headings;
}
}
What am I doing wrong?
This is what I see when I try to download the Excel file https://ibb.co/gyJ7khP