Home > database >  Fetching data in specific table and insert them in an other table using laravel and eloquent
Fetching data in specific table and insert them in an other table using laravel and eloquent

Time:06-09

I try to retrieve the information from a table in my database to insert it into another table immediately using a loop for to browse it but it only returns me a single element can help me please to solve this I struggle since a moment.

$data = Portefeuille::where("portefeuilles.Cloture", "=", 0)
    ->where("portefeuilles.Octroye", "=", 1)
    ->join('echeanciers', 'echeanciers.NumDossier', '=', 'portefeuilles.NumDossier')
    ->where("echeanciers.DateTranch", "=", $dateDuJour)
    ->where("echeanciers.statutPayement", "=", 0)
    ->where("echeanciers.CapAmmorti", ">", 0)
    ->get();
    
    
    
for ($i = 0; $i < sizeof($data); $i  ) {
     return return response()->json([$data[$i]->NumDossier]);  //gives me only one value however I should get ten values.
}

CodePudding user response:

Because you are returning a response inside your for loop so on its first iteration it returns the response

for ($i = 0; $i < sizeof($data); $i  ) {
      $response[]= $data[$i]->NumDossier; 
 }
 
return response()->json($response);

Suggestion: Instead of using the for loop you can use the foreach loop

foreach($data as $item) {
      $response[]= $item->NumDossier; 
 }
 
return response()->json($response);

CodePudding user response:

If you only need an array of the attribute NumDossier and have relations in place, you can do it like this

$numDossiers = Portefeuille::query()
    ->whereHas('echeancier', function($echeancier) use($dateDuJour) {
        $echeancier->where('dateTranch', '=', $dateDuJour)
            ->where('statutPayement', '=', 0)
            ->where('CapAmmorti', '>', 0);
    })
    ->where('Cloture', '=', 0)
    ->where('Octroye', '=', 1)
    ->pluck('NumDossier')->toArray();

return return response()->json($numDossiers);
  • Related