How to get average of column values in laravel
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
Averages are often used to analyze large datasets or draw meaningful conclusions from numerical data. In a Laravel application, handling such calculations is straightforward due to the availability of various built-in tools and methods that handle iterations and mathematical operations.
Understanding Arrays in Laravel
Before delving into the average calculation, let us first understand arrays in Laravel. An array is a data structure used to store multiple values of the same type under one variable name. In Laravel applications, arrays are represented using the array() function or collect() method for non-homogeneous collections.
Calculating Average Values Using Built‑in Methods
For numerical values stored in a column, Laravel provides several methods to calculate the average. These include:
1.array_sum(): This function returns the sum of all the numbers in an array. It is a built-in PHP method that works well with arrays containing integers or floating-point numbers. You can use it in Laravel as follows:
```php
$starValues = [1, 3, 3, 1, 2, 5, 3]; // Sample array of star values
$sumOfStars = array_sum($starValues); // Calculate the sum of star values
$averageStar = ($sumOfStars) / count($starValues); // Get the average by dividing the sum by the total number of elements in the array
```
2. collect(): If you have a non-homogeneous collection, you can first convert it to an array using Laravel's collect() method and then use the previously mentioned methods on the transformed array. Here's how:
```php
$starCollection = collect([['star' => 1], ['star' => 3], ['star' => 3], ['star' => 1], ['star' => 2], ['star' => 5], ['star' => 3]]); // Sample collection of stars with their values
$starsAsArray = $starCollection->map(function ($item) { return $item['star']; })->toArray(); // Transform the collection to an array containing only star values
```
Calculating Average Values Using Laravel Collections
Laravel provides a powerful tool called collections that allow you to perform various calculations, transformations, and manipulations on arrays easily. One of these methods is the avg(), which calculates the average value of all the elements in your array or collection:
Summary and Conclusion
In Laravel applications, calculating averages for numerical values is made simple with various inbuilt functions and tools. You can either use PHP's native array functions such as array_sum() or Laravel's collections to perform the calculations. This blog post provided a comprehensive answer to this question by explaining the concepts, demonstrating code snippets, and suggesting best practices. Remember to always validate your inputs when working with user-supplied data in real-world scenarios.