Write data to Laravel Restful API via JSON

Asked

Viewed 112 times

0

I’m trying to write data to a Restful API in Laravel through a JSON, but I can’t record 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']    
        ]);
  }

}

This way, the POST in the storeapi function only records the first group of data you have in JSON, the second does not write. I followed this article to be able to record: https://stackoverflow.com/questions/48861486/laravel-5-6-bulk-inserting-json-data

1 answer

1

Problem solved. The problem was the Return you had in 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.