Better to establish a proper relationship between Location and Appointment models; e.g. an Appointment belongsTo a Location - appt_location should instead be a foreign key ID of a Location, i.e. location_id
May 30, 2023
6
Level 1
Nested foreach loops with eloquent
Hi guys/gals! Bit of a noob question here :)
- I have a (list) or array of location names.
- I have an appointments table with a row named 'locations'.
What I need to do is: for-each location, query and count how many appointments are at a specific location. Here's my current non-working code
$locations = myLocationArray;
foreach ($locations as $location)
{
$q= Appointment::where('appt_type', 'Install')->where('appt_location', $location)->get();
}
dd($q);
Of course I'm not getting what I'm expecting because It only return the last iteration.
Thanks in advance for any help!
Level 11
@ntseles try
$locations = ['location1', 'location2', 'location3']; // Replace with your actual location array
$result = [];
foreach ($locations as $location) {
$count = Appointment::where('appt_type', 'Install')
->where('appt_location', $location)
->count();
$result[$location] = $count;
}
dd($result);
1 like
Please or to participate in this conversation.