I want to go through an array that comes to me from the view and insert it into the database, but it only enters the last array.
This is the array I send (I send it as json and convert it to array in controller)
Controller where to get the array:
$producto= new producto();
$productos=json_decode($request->productos);
// NO ME RECORRE EL ARRAY, SÓLO ME MUESTRA EL ÚLTIMO INGRESADO
/* foreach ($productos as $p) {
$array=[
'codigo'=>$p->codigo,
'cantidad'=>$p->cantidad,
'descripcion'=>$p->descripcion,
'valor'=>$p->valor,
'total'=>($p->valor * $p->cantidad),
'fecha'=> $p->fecha,
];
} */
//SI DEJO PRODUCTOS[$I] ME AGREGA EL ÚLTIMO ARRAY, SI DEJO PRODUCTOS[$J]
ME AGREGA EL PRIMER ARRAY
$j=0;
for($i=0;$i<count($productos);$i++){
$producto->codigo=$productos[$i]->codigo;
$producto->cantidad=$productos[$i]->cantidad;
$producto->descripcion=$productos[$i]->descripcion;
$producto->valor=$productos[$i]->valor;
$producto->total=($productos[$i]->cantidad * $productos[$i]->valor);
$producto->fecha=$productos[$i]->fecha;
$producto->save();
$j++;
}
I have tried several methods that I have searched here on the page but I have not reached a solution. I hope you can help me.
The solution was as simple as instantiating the product model within the for loop:
That way I insert all the values that are passing in the array to the database.