Find max value of a column in laravel

LaravelLaravel 5Eloquent

Laravel Problem Overview


The problem started because I have a table (Clientes), in which the primary key is not auto-incremental. I want to select the max value stored in a column database.

Like this select, but with eloquent ORM (Laravel):

SELECT MAX(Id) FROM Clientes

How can I do this?

I tried:

Cliente::with('id')->max(id);
Cliente::select('id')->max(id);

I prefer not to make a simple raw SELECT MAX(ID) FROM Clientes

I cannot make it.

Thanks all!

Laravel Solutions


Solution 1 - Laravel

The correct syntax is:

Cliente::max('id')

https://laravel.com/docs/5.5/queries#aggregates

Solution 2 - Laravel

Laravel makes this very easy, in your case you would use

$maxValue = Cliente::max('id');

But you can also retrieve the newest record from the table, which will be the highest value as well

$newestCliente = Cliente::orderBy('id', 'desc')->first(); // gets the whole row
$maxValue = $newestCliente->id;

or for just the value

$maxValue = Cliente::orderBy('id', 'desc')->value('id'); // gets only the id

Or, if you have a created_at column with the date you could get the value like this

$maxValue = Cliente::latest()->value('id');

Relevant Laravel Documentation: https://laravel.com/docs/5.5/queries#aggregates

Solution 3 - Laravel

    $maxValue = DB::table('Clientes')->max('id');

Solution 4 - Laravel

Cliente::where('column_name', $your_Valu)->max('id') // You get any max column  

Solution 5 - Laravel

We can use the following code :

 $min_id = DB::table('table_name')->max('id');

https://laravel.com/docs/8.x/queries#aggregates

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuido CaffaView Question on Stackoverflow
Solution 1 - LaravelAlexey MezeninView Answer on Stackoverflow
Solution 2 - LaravelMatthew MathiesonView Answer on Stackoverflow
Solution 3 - LaravelrashedcsView Answer on Stackoverflow
Solution 4 - LaravelMd HasanView Answer on Stackoverflow
Solution 5 - LaravelNarendraView Answer on Stackoverflow