0
0
Laravelframework~20 mins

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

Choose your learning style9 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.