In this article we will learn to use aggregate function max in laravel eloquent and query builder. Laravel itself provide inbuilt method to max
the columns like in MySQL or SQL based database we can do max of columns using max aggregate function.
Laravel eloquent or query builder max
method do the same as aggregate function. Laravel max accepts one parameter as column name.
Here is the syntax
Model::max(COLUMN_NAME);
//or
Model::select(\DB::raw("MAX(COLUMN_NAME), other_columns "))->get(); // or first()
//or
\DB::table('table_name')->max(COLUMN_NAME);
//or
\DB::table('table_name')->select(\DB::raw("MAX(COLUMN_NAME), other_columns "))->first()
In the above syntax we have used 4 examples to show all possibilities to use max aggregate function in laravel.
First is using the Model and max method of eloquent. Second is Model with select and Db::raw class.
In the third example we have used QueryBuilder DB class and table function to use max method of it.
And final example is query builder with select and db raw to use Max method of MySQL or SQL.
Result of above query will be:
select MAX(column_name) from `table`
//OR
select MAX(column_name), other_columns from `table`
Laravel max using native eloquent and raw query
Let’s understand laravel max in eloquent query with example
Example 1 – Laravel max aggregate function query using eloquent max method
So in this example i will use laravel query builder or eloquent max method to do the max 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::max('like_count');
\\or
DB::table('articles')->max('like_count');
}
}
Output will be :
select max(`like_count`) from `articles`
Example 2 – Laravel max query using raw query
In this example i will use laravel query builder DB::raw
method with select to max 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('max(like_count), aticles.*'))->get();
\\or
$Article = Article::selectRaw( 'max(like_count), articles.*')->get();
\\OR
DB::table('articles')->select(\DB::raw('max(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 max method.
Output will be :
select max(`like_count`), `aticles`.`*` from `articles`
Also Read : Laravel sum in eloquent query with example