Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gaspy's avatar
Level 1

SUM on a related model field

Let's say I have an Employee model that belongsTo a Department model. I can get department and the number of employees in each department like this:

$depts = Department::withCount('employees')->get();

Now, let's say each employee has a salary and when I get the department list, I need to get the sum of employee salaries for each department. How would I do that?

0 likes
3 replies
staudenmeir's avatar
Level 24

Use this:

$depts = Department::withCount([
    'employees as salaries' => function($query) {
        $query->select(DB::raw('sum(salary)'));
    }
])->get();

Please or to participate in this conversation.