[英]Laravel Export: Attempt to read property "second_key" on null
I need to export data with Laravel Export, but the code return ErrorException: Attempt to read property "second_key"
on null
.我需要使用 Laravel Export 导出数据,但代码返回 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: excel 单元格返回相同的结果:
{
"id": 282,
"second_key": "second_value",
"third_key": "6200",
"fourth_key": "0000",
"fifth_key": 28
}
As @dbf said in the comment section, I have to handle empty rows.正如@dbf在评论部分所说,我必须处理空行。 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
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.