I am trying to get data for each id using foreach. But when code run it get only data for 1 ID.. Following is the code
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')- >pluck('buffaloID')->toArray();
foreach ($buffalidforavgmilk as $id) {
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->pluck('buffaloID')->toArray();
dd([$buffalidforavgmilk,$milkperid]);
}
Output
array:2 [▼
0 => array:4 [▼
0 => "Buffalo-01"
1 => "Buffalo-02"
2 => "Buffalo-03"
3 => "Buffalo-04"
]
1 => array:5 [▼
0 => "Buffalo-01"
1 => "Buffalo-01"
2 => "Buffalo-01"
3 => "Buffalo-01"
4 => "Buffalo-01"
]
]
Here Loop giving only 1 ID where as required array for all 4 ID ( for Test, i try to get only buffaloID)
Thanks in Advance
CodePudding user response:
dd
interrupts execution. If you wanted to dump every result and then stop execution, you should have used dump
instead
foreach ($buffalidforavgmilk as $id) {
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->pluck('buffaloID')->toArray();
dump([$buffalidforavgmilk,$milkperid]);
}
dd('Done');
This is not ideal though. You are making a query in each iteration of the loop.
One way you could remove the foreach is to change your query to use whereIn
.
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->pluck('buffaloID')->toArray();
$milkperids = Buffalomilkrecord::whereIn('buffaloID', $buffalidforavgmilk)->pluck('buffaloID')->toArray();