Bird
Raised Fist0
Laravelframework~20 mins

Aggregates (count, sum, avg) in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Laravel Aggregates Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Laravel Eloquent aggregate query?
Consider a Laravel model Order with a total_price column. What does this code return?

Order::sum('total_price');
Laravel
use App\Models\Order;

$total = Order::sum('total_price');
echo $total;
AThe count of all orders in the database
BThe sum of all values in the total_price column across all orders
CThe average value of total_price for all orders
DThe maximum value of total_price among all orders
Attempts:
2 left
💡 Hint
Think about what the sum() method does in Laravel Eloquent.
📝 Syntax
intermediate
2:00remaining
Which option correctly counts the number of users with active status in Laravel?
You want to count users where the status column equals 'active'. Which code snippet is correct?
Laravel
use App\Models\User;

$count = ???;
echo $count;
AUser::where('status', 'active')->count();
BUser::count()->where('status', 'active');
CUser::where('status', 'active')->sum();
DUser::sum('status', 'active');
Attempts:
2 left
💡 Hint
Remember that count() is called after filtering with where().
🔧 Debug
advanced
2:00remaining
Why does this Laravel query cause an error?
Examine the code below:

$average = Product::avg();

What error will this produce and why?
Laravel
use App\Models\Product;

$average = Product::avg();
AReturns average of all columns automatically
BReturns 0 because no column specified
CError: Missing argument 1 for avg(), column name is required
DSyntaxError due to missing parentheses
Attempts:
2 left
💡 Hint
Check the method signature for avg() in Laravel Eloquent.
❓ state_output
advanced
2:00remaining
What is the value of $count after running this Laravel code?
Given the following code:

$count = User::where('age', '>', 30)->count();

Assuming the database has 5 users older than 30, what is the value of $count?
Laravel
use App\Models\User;

$count = User::where('age', '>', 30)->count();
A5
B0
CNumber of all users regardless of age
DThrows an exception
Attempts:
2 left
💡 Hint
The where() filters users older than 30 before counting.
🧠 Conceptual
expert
2:00remaining
Which Laravel aggregate method returns a float value representing the average of a column?
Select the method that returns the average value of a numeric column as a float in Laravel Eloquent.
Amax()
Bsum()
Ccount()
Davg()
Attempts:
2 left
💡 Hint
Think about which aggregate calculates the mean value.

Practice

(1/5)
1. What does the count() method do in Laravel Eloquent?
easy
A. Returns the number of records matching the query
B. Calculates the sum of a column
C. Finds the average value of a column
D. Deletes all records in the table

Solution

  1. Step 1: Understand the purpose of count()

    The count() method counts how many records match the query conditions.
  2. Step 2: Compare with other aggregate methods

    Unlike sum() or avg(), count() returns a number of rows, not a calculation on column values.
  3. Final Answer:

    Returns the number of records matching the query -> Option A
  4. Quick Check:

    count() = number of records [OK]
Hint: count() counts rows, sum() and avg() work on columns [OK]
Common Mistakes:
  • Confusing count() with sum() or avg()
  • Thinking count() returns column values
  • Assuming count() deletes records
2. Which of the following is the correct syntax to get the sum of the price column using Eloquent?
easy
A. Product::sum(['price']);
B. Product::sum(price);
C. Product->sum('price');
D. Product::sum('price');

Solution

  1. Step 1: Identify correct method call syntax

    In Laravel Eloquent, static calls use double colon :: and column names must be strings in quotes.
  2. Step 2: Check each option

    Product::sum('price'); uses Product::sum('price'); which is correct. Product::sum(price); misses quotes, C uses arrow on class, D passes array incorrectly.
  3. Final Answer:

    Product::sum('price'); -> Option D
  4. Quick Check:

    sum('column') needs quotes and :: [OK]
Hint: Use quotes around column name and :: for static call [OK]
Common Mistakes:
  • Omitting quotes around column name
  • Using -> instead of :: on model class
  • Passing column name as array
3. Given the code:
$total = Order::where('status', 'completed')->sum('amount');

What does $total contain?
medium
A. The count of orders with status 'completed'
B. An error because sum() cannot be used with where()
C. The sum of 'amount' for orders with status 'completed'
D. The average 'amount' for all orders

Solution

  1. Step 1: Understand the query filter

    The where('status', 'completed') filters orders to only those completed.
  2. Step 2: Apply the sum aggregate

    The sum('amount') adds up the 'amount' values of the filtered orders.
  3. Final Answer:

    The sum of 'amount' for orders with status 'completed' -> Option C
  4. Quick Check:

    where() filters, sum() adds column values [OK]
Hint: where() filters rows, sum() adds column values of filtered rows [OK]
Common Mistakes:
  • Thinking sum() returns count of rows
  • Believing sum() cannot be chained with where()
  • Confusing sum() with avg()
4. What is wrong with this code snippet?
$average = User::avg(age);
medium
A. avg() requires a second parameter
B. Missing quotes around the column name 'age'
C. avg() cannot be used on User model
D. Using avg() without where() causes error

Solution

  1. Step 1: Check method parameter syntax

    The avg() method requires the column name as a string, so it must be quoted.
  2. Step 2: Identify the error cause

    Without quotes, PHP treats age as a constant or variable, causing an error or unexpected behavior.
  3. Final Answer:

    Missing quotes around the column name 'age' -> Option B
  4. Quick Check:

    Column names must be strings in quotes [OK]
Hint: Always quote column names in aggregate methods [OK]
Common Mistakes:
  • Omitting quotes around column names
  • Thinking avg() needs multiple parameters
  • Assuming avg() requires where()
5. You want to get the average price of products that are in stock (stock > 0). Which Eloquent query is correct?
hard
A. Product::where('stock', '>', 0)->avg('price');
B. Product::avg('price')->where('stock', '>', 0);
C. Product::where('stock', '>', 0)->sum('price') / Product::count();
D. Product::sum('price')->where('stock', '>', 0) / Product::count();

Solution

  1. Step 1: Filter products with stock > 0

    The where('stock', '>', 0) filters only products that are in stock.
  2. Step 2: Calculate average price of filtered products

    The avg('price') calculates the average price of those filtered products.
  3. 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.
  4. Final Answer:

    Product::where('stock', '>', 0)->avg('price'); -> Option A
  5. Quick Check:

    Filter first, then aggregate [OK]
Hint: Chain where() before avg() to filter then calculate [OK]
Common Mistakes:
  • Calling aggregate before where()
  • Manually dividing sum by count without filtering
  • Mixing sum() and avg() incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard