Laravel Get Max Value of Column Example
Hi Dev,
This extensive guide will teach you laravel get max value of column. I’m going to show you about laravel get row with max value. This post will give you a simple example of get max value of a column in laravel. we will help you to give an example of get max value from collection laravel.
There are several ways to get get max id in laravel. i will give you three example using max(), latest() and orderBy() method. so, let's see the one-by-one example.
Example 1: using max()
app/Http/Controllers/DemoController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$maxID = Post::max("id");
dd($maxID);
}
}
Output:
7
Example 2: using latest()
app/Http/Controllers/DemoController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$maxID = Post::latest()->value('id');
dd($maxID);
}
}
Output:
7
Example 3: using orderBy()
app/Http/Controllers/DemoController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class DemoController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$maxID = Post::orderBy('id', 'desc')->value('id');
dd($maxID);
}
}
Output:
7
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent doesntHave() Condition Example
- Laravel Eloquent whereRelation() Condition Example
- Laravel Eloquent Group By Year with Sum Example
- Laravel Eloquent Group By with Month and Year Example
- Laravel Eloquent Left Join Where Null Condition Example
- Laravel Eloquent firstOr() Example
- Laravel Eloquent Delete Record By ID Example
- Delete All Records from Table in Laravel Eloquent
- Laravel Eloquent take() and skip() Query Example
- Laravel Eloquent whereNull() Query Example
- Multiple orWhere Condition in Laravel Eloquent
- Laravel Eloquent Where Query Examples
- Laravel Has Many Through Eloquent Relationship Tutorial
- How to Get Query Log in Laravel Eloquent?