Return employee count based on relationship

Viewed 36

I have a employees table and a attendances table

In employees Model

public function Attendance(){
    return $this->hasMany(Attendance::class, 'employees_id', 'id');
}

Attendances table i have these column id, employees_id, in_time, out_time, attendance_status_id, remarks

I want return those employee who has al least one attendance for a specific month which i will input in month field and it will filter based on in_time column

1 Answers

You can use the has() function when getting the Employee details. The has will only return those records if the Employee has any relational data in the Attendance table. You can also refer this link.

$employees = Employee::has('Attendance')->get();

Now you can simply use the count() function the display the total Attendance of the Employee. For the count please refer this link.

@foreach ($employees as $employee)
    Total attendance: {{ $employee->Attendance->count() }}
@endforeach
Related