Reputation: 45
I want to count the total number of employees per Department. For example, there are 13 IT Department employees, I want to get the total number of employees per department in Laravel.
DepartmentController.php
public function index()
{
$departments = Department::paginate(5);
return view('system-mgmt/department/index', ['departments' => $departments]);
}
Upvotes: 1
Views: 700
Reputation: 5735
If you've properly set up your Department
model like this:
class Department extends Model
{
// ...
public function employees()
{
return $this->hasMany(\App\Models\Employee::class);
}
// ...
}
DepartmentController.php
public function index()
{
$departments = Department::with('employees')->paginate(5);
return view('system-mgmt/department/index', ['departments' => $departments]);
}
You can do the following in your blade view:
<table>
<thead>
<tr>
<th>Department Name</th>
<th>Total Employees</th>
</tr>
</thead>
<tbody>
@foreach($departments as $department)
<tr>
<td>{{ $department->name }}</td>
<td>{{ $department->employees->count() }}</td>
</tr>
@endforeach
</tbody>
</table>
Alternatively you can do:
DepartmentController.php
public function index()
{
$departments = Department::withCount('employees')->paginate(5);
return view('system-mgmt/department/index', ['departments' => $departments]);
}
Your blade view:
<table>
<thead>
<tr>
<th>Department Name</th>
<th>Total Employees</th>
</tr>
</thead>
<tbody>
@foreach($departments as $department)
<tr>
<td>{{ $department->name }}</td>
<td>{{ $department->employees_count }}</td>
</tr>
@endforeach
</tbody>
</table>
Upvotes: 2