Write data in API RestFul Laravel through JSON

-1

I'm trying to write data to a Restful API in Laravel via a JSON, but I can not write more than one group of information when the file has more than one.

"data": [    {
   "client_id": "3",
   "veiculo_id": "3",
   "carreta1_id": "3",
   "carreta2_id": "3",
   "motorista1_id": "3",
   "motorista2_id": "3",
   "embarcador_id": "3",
   "inicioprevisao": "2018-10-10 11:00:00",
   "fimprevisao": "2018-10-10 18:00:00",
   "nroliberacao": "3"
 },    
  {
   "client_id": "4",
   "veiculo_id": "4",
   "carreta1_id": "4",
   "carreta2_id": "4",
   "motorista1_id": "4",
   "motorista2_id": "4",
   "embarcador_id": "4",
   "inicioprevisao": "2018-10-10 11:00:00",
   "fimprevisao": "2018-10-10 18:00:00",
   "nroliberacao": "4"
   }   

]}

This is my Controller:

public function storeapi(Request $request)
{
  $array = $request->all();
    foreach ($array['data'] as $row) {
        return Sm::create([
            'client_id' => $row['client_id'],
            'veiculo_id' => $row['veiculo_id'],
            'carreta1_id' => $row['carreta1_id'],
            'carreta2_id' => $row['carreta2_id'],
            'motorista1_id' => $row['motorista1_id'],
            'motorista2_id' => $row['motorista2_id'],
            'embarcador_id' => $row['embarcador_id'],
            'inicioprevisao' => $row['inicioprevisao'],
            'fimprevisao' => $row['fimprevisao'],
            'nroliberacao' => $row['nroliberacao']    
        ]);
  }

}

In this way, the POST in storeapi function only writes the first group of data it has in JSON, the second does not record. I followed this article to get record: link

    
asked by anonymous 03.10.2018 / 02:07

1 answer

0

Problem solved. The problem was the return I had on the create call.

$array = $request->all();
$insertedIds = [];
    foreach ($array['data'] as $row) {
        $newSm = Sm::create([
            'client_id' => $row['client_id'],
            'veiculo_id' => $row['veiculo_id'],
            'carreta1_id' => $row['carreta1_id'],
            'carreta2_id' => $row['carreta2_id'],
            'motorista1_id' => $row['motorista1_id'],
            'motorista2_id' => $row['motorista2_id'],
            'embarcador_id' => $row['embarcador_id'],
            'inicioprevisao' => $row['inicioprevisao'],
            'fimprevisao' => $row['fimprevisao'],
            'nroliberacao' => $row['nroliberacao']    
        ]);
        $insertedIds[] = $newSm->id;
  }
  //Now we can return an array with the inserted elements' IDs
  //In this case, since this is coming from a JSON, we'll answer the same way.
  return response()->json($insertedIds);
    
03.10.2018 / 06:19