Reputation: 295
I want to get total minutes. Example: joylinkhk 240 + 180 = 420. How can I get a total minute of a specific user?
controller
public function search(Request $request) {
$date = explode(' - ', $request->date);
$auth = Auth::user();
$hourLog = Hourlog::with('project', 'user');
if ($auth->user_type == 1) {
$hourLog->where("user_id", $auth->id);
}
$data = [
"date" => $date,
// 'projects' => Project::whereIn('id', $request->project)->get(),
'projects' => Project::with('users')->whereIn('id', $request->project)->get(),
'users' => User::with(['hourlog' => function ($query) use ($request) {
$query->whereIn('project_id', $request->project);
}])->whereIn('id', $request->user)->get(),
];
return view('cms.projectreport.projectreport-list', $data);
}
HTML view
@foreach($users as $user)
<tr>
<td>{{$user->name}}
</td>
@foreach($user->hourlog as $hourlogs)
<td>{{$hourlogs->hour_work}}
</td>
@endforeach
</tr>
@endforeach
Upvotes: 0
Views: 117
Reputation: 6058
As @danny-van-der-sluijs said, you can use sum
on a collection
@foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
@foreach($user->hourlog as $hourlogs)
<td>{{$hourlogs->hour_work}}</td>
@endforeach
</tr>
@endforeach
<tr>
<td>Grand Total</td>
<td>{{ $users->sum(fn($user) => $user->hourlog->sum('hour_work')) }}</td>
</tr>
Note:
$users->sum(fn($user) => $user->hourlog->sum('hour_work'))
Is an arrow function that came with php 7.4, If you are using a version below 7.4 you have to do it like this
$users->sum(function($user) {
return $user->hourlog->sum('hour_work');
});
Upvotes: 1
Reputation: 34688
You can sum in foreach
loop, but get the result outside of foreach
loop. You need to define first the variable outside of foreach $sum_total = 0;
, then you can sum inside foreach like this :
<?php $sum_total = 0; ?> // define here
@foreach($users as $user)
<tr>
<td>{{$user->name}}
</td>
@foreach($user->hourlog as $hourlogs)
<td>{{$hourlogs->hour_work}}
</td>
<?php
$sum_total += (intval)$hourlogs->hour_work
?>
@endforeach
</tr>
<tr>
<td>{{ $sum_total }}</td>
</tr>
@endforeach
Upvotes: 0
Reputation: 326
Laravel collections are very powerful and offer such functionality out of the box.
Below is a example of how you can take a collection of arrays and sum by its property hour_work
. The collect function is a quick way to create a collection like the $user->hourlog
already is.
collect([
['hour_work' => 198],
['hour_work' => 93],
['hour_work' => 51],
['hour_work' => 112],
])->sum('hour_work');
// Result: 454
Upvotes: 3