0
0
Laravelframework~30 mins

Aggregates (count, sum, avg) in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Laravel Aggregates: Count, Sum, and Average
📖 Scenario: You are building a simple Laravel application to manage sales data for a small store. You want to calculate some summary statistics like the total number of sales, the total revenue, and the average sale amount.
🎯 Goal: Build a Laravel Eloquent query that uses aggregate functions count(), sum(), and avg() on a Sale model to get the total sales count, total revenue, and average sale amount.
📋 What You'll Learn
Create a Sale model with a price attribute
Define a variable to hold a minimum price filter
Use Eloquent aggregate methods count(), sum(), and avg() with the filter
Store the results in variables named totalSales, totalRevenue, and averageSale
💡 Why This Matters
🌍 Real World
Stores and businesses often need to calculate total sales, revenue, and average sale amounts to understand performance.
💼 Career
Knowing how to use Laravel collections and aggregate functions is essential for backend developers working with data summaries and reports.
Progress0 / 4 steps
1
Create the Sales Data Array
Create a variable called sales as a collection of arrays with these exact entries: ['price' => 100], ['price' => 200], ['price' => 300], ['price' => 400], ['price' => 500].
Laravel
Need a hint?

Use collect([]) to create a Laravel collection with the given arrays inside.

2
Set a Minimum Price Filter
Create a variable called minPrice and set it to 200 to filter sales with price greater or equal to this value.
Laravel
Need a hint?

Just create a variable $minPrice and assign the number 200.

3
Filter Sales and Calculate Aggregates
Use the filter() method on $sales to keep only sales with price greater or equal to $minPrice. Then create variables totalSales with the count of filtered sales, totalRevenue with the sum of price, and averageSale with the average price.
Laravel
Need a hint?

Use filter() with a callback to keep sales with price >= $minPrice. Then use count(), sum('price'), and avg('price') on the filtered collection.

4
Return the Aggregates in an Array
Create a variable called summary that is an array with keys 'totalSales', 'totalRevenue', and 'averageSale' set to the respective variables.
Laravel
Need a hint?

Create an associative array $summary with keys matching the variable names and assign the variables as values.