[Bug]: Undefined array key #3328
-
Is the bug applicable and reproducable to the latest version of the package and hasn't it been reported before?
What version of Laravel Excel are you using?3.1.32 What version of Laravel are you using?8.40.0 What version of PHP are you using?8.0.9 Describe your issueI can't import data from xlsx file. It shows error undefined array key. How can the issue be reproduced?Here's my controller, import file class, the error message & excel file : <?php
namespace App\Http\Controllers;
use App\Imports\CitizensImport;
use Illuminate\Http\Request;
class CitizenImportController extends Controller
{
public function __invoke()
{
(new CitizensImport())->import(request()->file('file'));
}
} <?php
namespace App\Imports;
use App\Models\User;
use App\Models\Citizen;
use Maatwebsite\Excel\Row;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithUpserts;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
class CitizensImport implements ToCollection, WithHeadingRow
{
use Importable;
public function collection(Collection $rows)
{
foreach ($rows as $row) {
// dd($row['nama']);
// $data = $row->toArray();
// dd($data);
$user = User::create([
'puskesmas_id' => 1,
'name' => $row['nama'],
'email' => $row['email'],
'phone_number' => $row['no_telepon'],
'password' => bcrypt($row['email']),
]);
$citizen = new Citizen();
$citizen->fill([
'nik' => $row['nik'],
'name' => $row['nama'],
'sex' => $row['jk_mf'],
'birth_date' => $row['tanggal_lahir_yyyy_mm_dd'],
'street_address' => $row['alamat_jalankompleks'],
'rt' => $row['rt'],
'rw' => $row['rw'],
'phone_number' => $row['no_telepon'],
'email' => $row['email'],
'village_id' => $row['desa_id'],
'puskesmas_id' => $row['puskesmas_id'],
'user_id' => $user->id,
]);
$citizen->user_id = $user->id;
$user->save();
}
}
public function uniqueBy()
{
return 'nik';
}
} What should be the expected behaviour?The data on the excel file should be inserted into database. |
Beta Was this translation helpful? Give feedback.
Answered by
patrickbrouwers
Aug 24, 2021
Replies: 1 comment 3 replies
-
You have to add checks yourself to see if the array key exists or not. Use |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
patrickbrouwers
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have to add checks yourself to see if the array key exists or not. Use
dd($row)
ordump($row)
to debug your implementation.