How to calculate total days in array
Hi all have array of contract start and end date need to sum them and get for exsabple 45 day total time
my array
^ Illuminate\Database\Eloquent\Collection {#2106 ▼
#items: array:7 [▼
0 => App\Modules\Contract\Models\Contract {#2107 ▼
#table: "contracts"
#dates: array:4 [▶]
#fillable: array:18 [▶]
#sortable: array:18 [▶]
#casts: array:6 [▶]
#dispatchesEvents: array:1 [▶]
#likeFields: array:16 [▶]
#boolFields: array:1 [▶]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:2 [▼
"contract_start_date" => "2022-06-24 05:06:18"
"contract_end_date" => "2022-06-28 05:06:18"
]
#original: array:2 [▶]
#changes: []
#classCastCache: []
#attributeCastCache: []
#dateFormat: null
#appends: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
1 => App\Modules\Contract\Models\Contract {#2126 ▶}
2 => App\Modules\Contract\Models\Contract {#2125 ▶}
3 => App\Modules\Contract\Models\Contract {#2124 ▶}
4 => App\Modules\Contract\Models\Contract {#2123 ▶}
5 => App\Modules\Contract\Models\Contract {#2122 ▶}
6 => App\Modules\Contract\Models\Contract {#2121 ▶}
]
#escapeWhenCastingToString: false
}
$day = 0;
foreach ($contracts as $contract) {
$start_date = Carbon::parse($contract->contract_start_date);
$end_date = Carbon::parse($contract->contract_end_date);
$day += $end_date->diffInDays($start_date);
}
You can greatly simplify is you (i) cast start_date and end_date as Carbon instances on the Contract Model and (ii) use the Collection's sum method:
$days = $contracts->sum(fn ($contract) => $contract->start_date->diffInDays($contract->end_date));
Furthermore, if it is useful, you could make an Accessor on the Model to calculate the Contract duration:
public function duration(): Attribute
{
return new Attribute(
get: fn () => $this->start_date->diffInDays($this->end_date)
);
}
Then the sum is even easier:
$days = $contracts->sum('duration');
Please or to participate in this conversation.