Laravel Eloquent ORM

Using Aggregates function with Laravel Eloquent, Query Builder

Image title

Once you have created a Eloquent model and its associated database table, you can start retrieving data from your database. Think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model.

Of course, in addition to retrieving models, you may use count,min,max,sum and avg aggregate function provided by Laravel to get the appropriate scalar value instead of a full model instance. You may call any of these methods after constructing your query:


<?php

use App\Product;

$count = Product::where('active', 1)->count();
$max = Product::where('active', 1)->max('price');
$min = Product::where('active', 1)->min('price');
$sum = Product::where('active', 1)->sum('price');
$avg = Product::where('active', 1)->avg('price');


If you have any other questions, experience or insights on "Using Aggregates function with Laravel Eloquent, Query Builder" please feel free to leave your thoughts in the comments bellow which might be helpful to someone!


Share your thoughts

You may use <pre> </pre> tag for writing multi lines code or <code> </code> tag for writing single line code in the comment section bellow.