I am trying to run a query multiple times with foreach loop
@ramniksingh Don’t 😬 That’s the very definition of the N+1 problem.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello Everyone, I have encountered a strange problem. I am trying to run a query multiple times with foreach loop and storing the results in an array to use later for some calculations.
Below is the detail:
This works
$test = DB::table('appcal')
->select('monthyear','appdate')
->whereDate('appdate','>=', '2018-04-01')
->get();
dd($test);
But this does not work
foreach($activities as $activity){
$qry[] = DB::table('appcal')
->select('monthyear','appdate')
->whereDate('appdate','>=', '2018-04-01')
->get();
}
dd($qry);
But this work
foreach($activities as $activity){
$qry[] = DB::table('appcal')
->select('monthyear','appdate')
->whereDate('appdate','=', '2018-04-01')
->get();
}
dd($qry);
Can you suggest what is the issue here? Am I doing something wrong ?
What should I correctly do to store the query results in an array to use later for some calculations.
Please or to participate in this conversation.