Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel return one record where max value

I'm trying to return one record with a max value as an object. When I do this:

public function highestExpense()
    {
        return auth()->user()->expenses()->max('amount');
    }

It works, and I get the highest value. But I want to have the whole record returned, so I also have access to the expense name, created_at, and so on.

This didn't work for me:

return auth()->user()->expenses()->max('amount')->get();

It seems like a simple solution but the answer is nowhere to be found.

like image 988
Hardist Avatar asked Jul 23 '17 08:07

Hardist


2 Answers

If I'm understanding your question correctly, to get the record that has the highest amount you could just add an orderBy and the grab the first row:

auth()->user()->expenses()->orderBy('amount', 'desc')->first();

This should give the expense with the highest amount.

Hope this helps!

like image 158
Rwd Avatar answered Oct 17 '22 10:10

Rwd


You can the Collection method sortByDesc like follow :

return auth()->user()->expenses()->sortByDesc('amount')->first();
like image 1
Abdeldjallil Hadji Avatar answered Oct 17 '22 08:10

Abdeldjallil Hadji