In this article we will learn to use aggregate function avg in laravel eloquent and query builder. Laravel itself provide inbuilt method to avg
the columns like in MySQL or SQL based database we can do avg of columns using avg aggregate function.
Avg method will give you the average of columns. For example if you have 10 rows and you want the average from a column X then you will get the average percentage from the 10 rows
Laravel eloquent or query builder avg
method do the same as aggregate function. Laravel avg accepts one parameter as column name.
Here is the syntax
Model::avg(COLUMN_NAME);
//or
Model::select(\DB::raw("avg(COLUMN_NAME), other_columns "))->get(); // or first()
//or
\DB::table('table_name')->avg(COLUMN_NAME);
//or
\DB::table('table_name')->select(\DB::raw("avg(COLUMN_NAME), other_columns "))->first()
In the above syntax we have used 4 examples to show all possibilities to use avg aggregate function in laravel.
First is using the Model and avg method of eloquent. Second is Model with select and Db::raw class.
In the third example we have used Query Builder DB class and table function to use avg method of it.
And final example is query builder with select and db raw to use avg method of MySQL or SQL.
Result of above query will be:
select avg(column_name) from `table`
//OR
select avg(column_name), other_columns from `table`
Let’s understand laravel avg in eloquent query with example
Example 1 – Laravel avg aggregate function query using eloquent avg method
So in this example i will use laravel query builder or eloquent avg method to do the avg of column.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$Article = Article::avg('like_count');
\\or
DB::table('articles')->avg('like_count');
}
}
Output will be :
select avg(`like_count`) from `articles`
Example 2 – Laravel avg query using raw query
In this example i will use laravel query builder DB::raw
method with select to avg the column
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$Article = Article::select(\DB::raw('avg(like_count), aticles.*'))->get();
\\or
$Article = Article::selectRaw( 'avg(like_count), articles.*')->get();
\\OR
DB::table('articles')->select(\DB::raw('avg(like_count), articles.*'))->first();
}
}
In the above example we have used articles table and created a model in our laravel application. Then we imported the necessary classes and used the avg method.
Output will be :
select avg(`like_count`), `aticles`.`*` from `articles`
Also Read : Laravel max in eloquent query with example