0
0
Laravelframework~5 mins

Aggregates (count, sum, avg) in Laravel

Choose your learning style9 modes available
Introduction

Aggregates help you quickly get totals or averages from your database without loading all data. They save time and make your app faster.

Counting how many users signed up today.
Adding up all sales to see total revenue.
Finding the average rating of a product.
Checking how many orders are pending.
Calculating the average age of members in a group.
Syntax
Laravel
Model::count();
Model::sum('column');
Model::avg('column');

Use count() to get the number of rows.

Use sum('column') and avg('column') to get totals and averages of a specific column.

Examples
Counts all users in the users table.
Laravel
User::count();
Adds up the total_price column from all orders.
Laravel
Order::sum('total_price');
Calculates the average rating from all reviews.
Laravel
Review::avg('rating');
Sample Program

This example shows how to count products that are in stock, sum all product prices, and find the average price using Laravel's aggregate methods.

Laravel
<?php
use App\Models\Product;

// Count how many products are in stock
$inStockCount = Product::where('in_stock', '>', 0)->count();

// Sum the prices of all products
$totalPrice = Product::sum('price');

// Average price of products
$averagePrice = Product::avg('price');

// Display results
echo "Products in stock: $inStockCount\n";
echo "Total price of products: $totalPrice\n";
echo "Average product price: $averagePrice\n";
OutputSuccess
Important Notes

Aggregates run directly in the database, so they are very fast.

You can add where clauses before aggregates to filter data.

Remember to import your model with use App\Models\ModelName;.

Summary

Aggregates help get counts, sums, and averages quickly.

Use count(), sum('column'), and avg('column') on your models.

They work well with filters like where to focus on specific data.