0

I have a json object that has objects inside like this:

{
  "configuracion_id": 16,
  "datos_clase": [
    {
      "periodo_id": 32,
      "total_calmado_movimiento": 1,
      "total_calmado_ritmo": 0,
      "total_intervalos_movimiento": 1,
      "total_intervalos_ritmo": 1,
      "total_nervioso_movimiento": 0,
      "total_nervioso_ritmo": 1
    },
    {
      "periodo_id": 30,
      "total_calmado_movimiento": 3,
      "total_calmado_ritmo": 0,
      "total_intervalos_movimiento": 2,
      "total_intervalos_ritmo": 2,
      "total_nervioso_movimiento": 0,
      "total_nervioso_ritmo": 1
    }
  ],
  "fecha": "30 March 2023",
  "puntuacion": 3,
  "student_id": 35
}

I have decoded it into an array and I want to access to every object of "datos_clase" to store each object into a new register of "DatumClass". I have done it like this:

public function postData(Request $request){
        $datos=$request->all();
        $datos1=json_encode($datos);

        
        Log::info('Request:'.$datos1);
        $datos1Array = json_decode($datos1, true);

        $datosClase=$datos1Array->datos_clase;

        $fecha = date('Y-m-d',strtotime($datos1Array['fecha']));
        

        Datum::create([
            'configuration_id' => $datos1Array['configuracion_id'],
            'student_id' => $datos1Array['student_id'],
            'fecha' => $fecha,
            'puntuacion' => $datos1Array['puntuacion'],
        ]);

        foreach($datosClase as $dato){
            DatumClass::create([
                
                'periodo_id' => $dato['periodo_id'],
                'total_intervalos_movimiento' => $dato['total_intervalos_movimiento'],
                'total_nervioso_movimiento' => $dato['total_nervioso_movimiento'],
                'total_calmado_movimiento' => $dato['total_calmado_movimiento'],
                'total_intervalos_ritmo' => $dato['total_intervalos_ritmo'],
                'total_nervioso_ritmo' => $dato['total_nervioso_ritmo'],
                'total_calmado_ritmo' => $dato['total_calmado_ritmo'],
            ]);
        }

        return $request->all();
        
    }

My idea is storing the array "datosClase" into an array and then use a foreach loop to store every element of that array into "DatumClass", but I get that error. Any idea? Thank you.

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
Luis Yiao
  • 3
  • 3
  • `$datos1Array->datos_clase;` is not valid if `$datos1Array` is an Array. `->` access is for Objects, not Arrays. Try `$datos1Array['datos_clase'];`; `[]` is for Arrays. – Tim Lewis Mar 31 '23 at 20:19

0 Answers0