Performance: Aggregates (count, sum, avg)
This affects how quickly the database returns summary data and how much data the server processes before sending results to the browser.
$count = User::count(); $sum = User::sum('orders_total');
$users = User::all(); $count = $users->count(); $sum = $users->sum('orders_total');
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Loading full dataset then counting/summing in PHP | N/A (server-side) | N/A | N/A | [X] Bad |
| Using database aggregate functions (count, sum, avg) | N/A (server-side) | N/A | N/A | [OK] Good |
count() method do in Laravel Eloquent?count()count() method counts how many records match the query conditions.sum() or avg(), count() returns a number of rows, not a calculation on column values.price column using Eloquent?:: and column names must be strings in quotes.Product::sum('price'); which is correct. Product::sum(price); misses quotes, C uses arrow on class, D passes array incorrectly.$total = Order::where('status', 'completed')->sum('amount');$total contain?where('status', 'completed') filters orders to only those completed.sum('amount') adds up the 'amount' values of the filtered orders.$average = User::avg(age);
avg() method requires the column name as a string, so it must be quoted.age as a constant or variable, causing an error or unexpected behavior.where('stock', '>', 0) filters only products that are in stock.avg('price') calculates the average price of those filtered products.Pass the test and this pattern moves unknown