Eloquent Aggregates: Count, Sum, Max, Min, Average

Updated: January 16, 2024 By: Guest Contributor Post a comment

Understanding Eloquent Aggregates

Laravel’s Eloquent ORM offers developers a beautifully simple ActiveRecord implementation for working with databases. In this guide, we’ll dive into one of its less-celebrated, yet highly powerful features: Aggregate methods. Eloquent allows you to perform a variety of aggregate operations such as count, sum, max, min, and average directly on your models. These methods provide a quick and easy way to gather statistics or summaries about the data in your database.

Without further ado, let’s begin our exploration of these Eloquent aggregate functions with some practical examples. Make sure you have your Laravel development environment set up before you proceed so you can follow along with the examples.

Performing a Basic Count Operation

Starting out simple, we’re going to use the count() method to determine the number of records in a table. Assume we have a User model representing the users table.

$userCount = User::count();

This code will output the total number of users in the table. This is essentially equivalent to the SQL query SELECT COUNT(*) FROM users.

Summing Up Column Values

If you want to sum a column’s values, use the sum() method. Let’s sum the salary field in our hypothetical Employee model.

$totalSalaries = Employee::sum('salary');

The $totalSalaries variable will hold the total sum of all the employees’ salaries. This method is doing something similar to SELECT SUM(salary) FROM employees.

Finding Maximum and Minimum Values

To retrieve the highest value in a given column, use the max() method:

$highestSalary = Employee::max('salary');

In contrast, for the lowest value, use min():

$lowestSalary = Employee::min('salary');

These will fetch the highest and lowest salary respectively, equivalent to SELECT MAX(salary) and SELECT MIN(salary) in SQL.

Calculating the Average

Calculating the average value of a column is done using the avg() or average() methods:

$averageSalary = Employee::avg('salary');

This will calculate the average salary of all employees equivalent to SELECT AVG(salary) FROM employees.

Using Aggregates on Relationship Queries

Eloquent simplifies dealing with relationships and allows the use of aggregates on them directly. If each user has multiple posts, we can count how many posts each user has:

$users = User::withCount('posts')->get();
\nforeach ($users as $user) {
    echo $user->posts_count . "\n";
}
\n// Outputs the number of posts each user has

This functionality is particularly handy when you’re dealing with collections of models and relationships.

Complex Aggregates with Grouping

Oftentimes, you may want to group your results by a certain field and perform aggregate operations on each group. With Eloquent, this is straightforward:

$salaryByDepartment = Employee::selectRaw('department, SUM(salary) as total_salary')
                        ->groupBy('department')
                        ->get();

This will give us the total salary for each department.

Filters and Aggregates

Aggregate methods can also be combined with Eloquent’s querying capabilities to apply filters. Suppose we only want to get the sum of salaries for employees in a particular department:

$totalDevelopmentSalaries = Employee::where('department', 'development')
                                    ->sum('salary');

This code will only give us the total sum of salaries for the ‘development’ department.

Conclusion

We’ve covered various ways to use Eloquent’s aggregate functions to perform essential database queries. Remember, Eloquent provides a beautiful, simple active record implementation for working with your database and by understanding these aggregate methods, you can write concise and effective queries for your data.