I have a list of clients who have many appointments in db. I want to iterate through the appointments totalling their duration for each client so I can create an invoice. When I run the below code the first client's appointments duration are added correctly. However my issue is, for the next client it seems to add the first clients duration too. Is array_sum the correct method?? What do i need to use if not?
foreach($clients as $client)
{
$appointments = Client::find($client->id)->appointments()->get();
foreach($appointments as $appointment)
{
$date1 = $appointment->starts_at;
$date2 = $appointment->ends_at;
$start = Carbon::parse($date1);
$end = Carbon::parse($date2);
$length = $start->diffinhours($end);
$duration[] = $length; //is this correct?
$total = array_sum($duration); //is this correct?
}
$invoice = new Invoice;
$invoice->total_hours = $total;
dd($invoice);
$invoice->save();
}
$appointments) make you total variable as 0 i.e.$total=0