Discover how a few simple functions can replace hours of tedious counting and adding!
Why Aggregates (count, sum, avg) in Laravel? - Purpose & Use Cases
Imagine you have a list of orders and you want to find out how many orders there are, the total sales amount, and the average order value by manually looping through each order.
Manually counting, adding, and averaging values means writing extra code, risking mistakes, and making your app slower as data grows. It's like counting coins one by one instead of using a calculator.
Laravel's aggregate functions like count(), sum(), and avg() do all the math for you in a simple, fast, and reliable way directly in the database.
$total = 0; $count = 0; foreach ($orders as $order) { $total += $order->amount; $count++; } $average = $count ? $total / $count : 0;
$count = Order::count(); $sum = Order::sum('amount'); $average = Order::avg('amount');
You can quickly get important summary numbers from your data without extra code or errors, making your app faster and easier to maintain.
For an online store, instantly showing how many products sold today, total revenue, and average sale price helps owners make smart decisions.
Manual calculations are slow and error-prone.
Laravel aggregates do the math efficiently in the database.
This saves time, reduces bugs, and improves app speed.
Practice
count() method do in Laravel Eloquent?Solution
Step 1: Understand the purpose of
Thecount()count()method counts how many records match the query conditions.Step 2: Compare with other aggregate methods
Unlikesum()oravg(),count()returns a number of rows, not a calculation on column values.Final Answer:
Returns the number of records matching the query -> Option AQuick Check:
count() = number of records [OK]
- Confusing count() with sum() or avg()
- Thinking count() returns column values
- Assuming count() deletes records
price column using Eloquent?Solution
Step 1: Identify correct method call syntax
In Laravel Eloquent, static calls use double colon::and column names must be strings in quotes.Step 2: Check each option
Product::sum('price'); usesProduct::sum('price');which is correct. Product::sum(price); misses quotes, C uses arrow on class, D passes array incorrectly.Final Answer:
Product::sum('price'); -> Option DQuick Check:
sum('column') needs quotes and :: [OK]
- Omitting quotes around column name
- Using -> instead of :: on model class
- Passing column name as array
$total = Order::where('status', 'completed')->sum('amount');What does
$total contain?Solution
Step 1: Understand the query filter
Thewhere('status', 'completed')filters orders to only those completed.Step 2: Apply the sum aggregate
Thesum('amount')adds up the 'amount' values of the filtered orders.Final Answer:
The sum of 'amount' for orders with status 'completed' -> Option CQuick Check:
where() filters, sum() adds column values [OK]
- Thinking sum() returns count of rows
- Believing sum() cannot be chained with where()
- Confusing sum() with avg()
$average = User::avg(age);
Solution
Step 1: Check method parameter syntax
Theavg()method requires the column name as a string, so it must be quoted.Step 2: Identify the error cause
Without quotes, PHP treatsageas a constant or variable, causing an error or unexpected behavior.Final Answer:
Missing quotes around the column name 'age' -> Option BQuick Check:
Column names must be strings in quotes [OK]
- Omitting quotes around column names
- Thinking avg() needs multiple parameters
- Assuming avg() requires where()
Solution
Step 1: Filter products with stock > 0
Thewhere('stock', '>', 0)filters only products that are in stock.Step 2: Calculate average price of filtered products
Theavg('price')calculates the average price of those filtered products.Step 3: Check other options for correctness
Product::avg('price')->where('stock', '>', 0); calls avg() before where(), which is invalid. Manual calculations with sum divided by count do not filter correctly or mix sum and count improperly.Final Answer:
Product::where('stock', '>', 0)->avg('price'); -> Option AQuick Check:
Filter first, then aggregate [OK]
- Calling aggregate before where()
- Manually dividing sum by count without filtering
- Mixing sum() and avg() incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
