Mark Anthony Legaspi
Mark Anthony Legaspi

Reputation: 45

How to count total number of employees in each department in Laravel

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]);
}

enter image description here

Upvotes: 1

Views: 700

Answers (1)

shaedrich
shaedrich

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

Related Questions