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...