简体   繁体   中英

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

在此处输入图像描述

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM