Search code examples
phplaraveleloquentmax

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.


Solution

  • 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!