previously, I have created a function to send data and it worked. but the data input method is only one by one.
and I think it's not efficient, then I try to send data in the form of json which will later be saved into the database.
this data uses 2 unique ids which are associated with 2 other tables.
this is my previous code.
$validator = Validator::make($request->all(),[
'nama_event'=>'required',
'nama_lengkap' => 'required|string',
'kehadiran'=>'boolean'
]);
if($validator->fails()){
return $this->error('Gagal', 500, [$validator->errors()]);
}
$event = Event::where('nama',$request->nama_event)->get();
$anggota = Anggota::where('nama_lengkap',$request->nama_lengkap)->get();
$presensi = Presensi::create([
'event_id' => $event[0]->id,
'anggota_id' => $anggota[0]->id,
'kehadiran' => $request->kehadiran,
]);
and this is my current code
$result = [];
$datas = $request->data;
foreach ($datas['data'] as $data) {
$event = Event::where('nama',$data['nama_event'])->get();
$anggota = Anggota::where('nama_lengkap',$data['nama_lengkap'])->get();
$result[] = [
'event_id' => $event[0]->id,
'anggota_id' => $anggota[0]->id,
'kehadiran' => $data['kehadiran'],
];
}
$presensi = Presensi::insert($result);
but i got an error like this.
"message": "Trying to access array offset on value of type null",
"exception": "ErrorException",
this is the JSON format I use
{
"data": {
"data": [
{
"nama_event": "event 1",
"nama_lengkap": "user 1",
"kehadiran": true
},
{
"nama_event": "event 1",
"nama_lengkap": "user 2",
"kehadiran": false
}
]
}
}
and, also I confuse how to deal with validator if using array. does anyone know what's wrong with my code?