Home > other >  Laravel 8 - POST JSON using foreach - API
Laravel 8 - POST JSON using foreach - API

Time:02-14

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?

CodePudding user response:

I replicated issue that you are facing and i hope that this helps.

There is no need to use get() and return collectoin and then access 0th element. Use first() that is returing single model instead. So you should try something like :

$result = [];
    $datas = $request->data;
    foreach ($datas->data as $data) {
        $event = Event::where('nama',$data->nama_event)->first();
        $anggota = Anggota::where('nama_lengkap',$data->nama_lengkap)->first();
        $kehadiran = $data->kehadiran;
        $result[] =[
            'event_id'  => $event->id,
            'anggota_id' => $anggota->id,
            'kehadiran' => $kehadiran,
        ];
    }
    
$presensi = Presensi::insert($result);
  • Related