3

I'm using Laravel 5.5, And I want to know how can we get highest value of each column in one query ?

Is that possible or we should query one by one ?

I tried below code.

DB::table('family')->max('children')->max('salary');

When I tried just DB::table('family')->max('children'), It works well. But when I try DB::table('family')->max('children')->max('salary'), I get below error

Call to a member function max() on string

  • What have you tried so far? Please see this guide on how to ask questions on Stack Overflow: [Link here](https://stackoverflow.com/help/how-to-ask) – Blundering Philosopher Dec 17 '17 at 12:57
  • @BlunderingPhilosopher i didnt try anything because i didnt know how to do that , just asked question to know –  Dec 17 '17 at 13:37

2 Answers2

1

Add max() with your eloquent to get the maximum value of each column value.

ModelName::select(DB::raw('MAX(column1) AS colum1'),DB::raw('MAX(colum2) AS colum2'))->get();

check this laravel docs

Edit: You can do it with query builder in laravel.

Community
  • 1
  • 1
ARUN Madathil
  • 896
  • 10
  • 16
  • when i try DB::table('family')->max('children) it works well , but when i try DB::table('family')->max('children)->max('salary') the result is "Call to a member function max() on string" –  Dec 17 '17 at 12:02
1

You can get either by single query.

$result = DB::table("family as f")
->select([DB::raw('MAX(f.children) AS children_max'),DB::raw('MAX(f.salary) AS salary_max')])
->groupBy('f.id')
->first();

Or using separate ->max() method.

$family = DB::table('family');
$max_children = $family->max('children');
$max_salary = $family->max('salary');

Get more details in other answer and in Laravel Docs

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109