I need to export data with Laravel Export, but the code return ErrorException: Attempt to read property "second_key"
on null
.
My code:
<?php
namespace App\Admin\Extensions;
use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
class DataExporter extends ExcelExporter implements FromQuery, WithMapping, ShouldAutoSize
{
protected $fileName = 'Export Data.xlsx';
public function headings(): array
{
return [
'ID',
'Title',
'Status',
'Gender',
'Data',
];
}
public function map($data): array
{
return [
$data->id,
$data->title,
$data->status,
$data->gender,
$data->json_data->second_key, // <-- Here's the error
];
}
}
I've tried to check using this:
print_r(json_encode($data->json_data));
and this is the result:
{
"id": 282,
"second_key": "second_value",
"third_key": "6200",
"fourth_key": "0000",
"fifth_key": 28
}
I've also done this:
return [
$data->id,
$data->title,
$data->status,
$data->gender,
$data->json_data //Without "second_key"
];
and the excel cell returns the same result:
{
"id": 282,
"second_key": "second_value",
"third_key": "6200",
"fourth_key": "0000",
"fifth_key": 28
}
CodePudding user response:
As @dbf said in the comment section, I have to handle empty rows. I have checked several times in the database, and maybe I missed that one blank row. Anyway, this is how I handle those values:
if (!isset($data->json_data->second_key)) {
$second_key = '-';
} else {
$second_key = $data->json_data->second_key;
}
return [
$data->id,
$data->title,
$data->status,
$data->gender,
$second_key
];