Reputation: 21
I have two tables employes and attendances . What I want is to sum work_time for each employe id and show in my view.
employes Table id attendances Table id employe_id work_time
I want to sum work_time column for specific employe id. I am new to laravel so how do I do that with laravel eloquent.
Employe.php
class Employe extends Model{
use HasFactory;
protected $fillable=['id','employe_code','employe_name','workplace'];
public function employee(){return $this->hasMany(Attendance::class);}}
Attendance.php
class Attendance extends Model{use HasFactory;
protected$fillable['id','employe_id','attendence_date','clock_in','clock_out','work_time','attendence_status'];
public function employe()
{return $this->belongsTo('App\Models\employe', 'employe_id');}}
AttendanceController
public function attendance(){
$attendances = Employe::all();
$hour = Attendance::where('employe_id',1)->sum('work_time');
return view('pages.Attendance.hour', compact('attendances','hour')); }
hour.blade.php
```
<table id="datatable" class="table table-hover table-sm table-bordered p-0" data-page-length="50"
style="text-align: center">
<thead>
<tr>
<th class="alert-success">#</th>
<th class="alert-success">employe_code</th>
<th class="alert-success">employe_name</th>
<th class="alert-success">work_time</th>
</thead>
<tbody>
@foreach($attendances as $attendances)
<tr>
<td></td>
<td>{{ $attendances->employe_code }}</td>
<td>{{ $attendances->employe_name }}</td>
<td>Hour {{ $hour }} </td>
</tr>
@endforeach
</table>
Upvotes: 0
Views: 62
Reputation: 17206
Only for Laravel 8.12 and above, you can use withSum()
First of all, correct the relation name in Employe.php
class Employe extends Model{
use HasFactory;
protected $fillable=['id','employe_code','employe_name','workplace'];
public function attendances(){ //<---- here
return $this->hasMany(Attendance::class);
}
}
Here is the controller
public function attendance(){
$attendances = Employe::query()->withSum('attendances', 'work_time')->get();
return view('pages.Attendance.hour', compact('attendances'));
}
And the blade (kept the variable name $attendances
but you should change it to employees)
<table id="datatable" class="table table-hover table-sm table-bordered p-0" data-page-length="50" style="text-align: center">
<thead>
<tr>
<th class="alert-success">#</th>
<th class="alert-success">employe_code</th>
<th class="alert-success">employe_name</th>
<th class="alert-success">work_time</th>
</thead>
<tbody>
@foreach($attendances as $employe)
<tr>
<td></td>
<td>{{ $employe->employe_code }}</td>
<td>{{ $employe->employe_name }}</td>
<td>Hour {{ $employe->attendances_sum_work_time }} </td>
</tr>
@endforeach
</table>
Upvotes: 1