Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max value of a column in laravel

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!

like image 885
Guido Caffa Avatar asked Dec 20 '17 21:12

Guido Caffa


2 Answers

The correct syntax is:

Cliente::max('id') 

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

like image 127
Alexey Mezenin Avatar answered Oct 10 '22 06:10

Alexey Mezenin


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

like image 39
Matthew Mathieson Avatar answered Oct 10 '22 06:10

Matthew Mathieson