ItSolutionStuff.com

Laravel Get Max Value of Column Example

By Hardik Savani • November 5, 2023
Laravel

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

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

šŸ“ŗ Subscribe on YouTube

We Are Recommending You

ā˜…

Laravel Eloquent doesntHave() Condition Example

Read Now →
ā˜…

Laravel Eloquent whereRelation() Condition Example

Read Now →
ā˜…

Laravel Eloquent Group By Year with Sum Example

Read Now →
ā˜…

Laravel Eloquent Group By with Month and Year Example

Read Now →
ā˜…

Laravel Eloquent Left Join Where Null Condition Example

Read Now →
ā˜…

Laravel Eloquent firstOr() Example

Read Now →
ā˜…

Laravel Eloquent Delete Record By ID Example

Read Now →
ā˜…

Delete All Records from Table in Laravel Eloquent

Read Now →
ā˜…

Laravel Eloquent take() and skip() Query Example

Read Now →
ā˜…

Laravel Eloquent whereNull() Query Example

Read Now →
ā˜…

Multiple orWhere Condition in Laravel Eloquent

Read Now →
ā˜…

Laravel Eloquent Where Query Examples

Read Now →
ā˜…

Laravel Has Many Through Eloquent Relationship Tutorial

Read Now →
ā˜…

How to Get Query Log in Laravel Eloquent?

Read Now →