1

I am using Laravel's DB::select to run a query to get a MAX() value. I only want the single column value from the single row result. What method do I use to get this from a DB::select() statement?

I found this answerenter link description here that proffered both pluck() and value(). The behavior of pluck() had changed since 5.3, so that wasn't the answer. However, when I used value(), I didn't get the value I was expecting. Instead I got an error about an array:

$query =  DB::select('SELECT max(sort) AS sort FROM man_pos WHERE manual_id = ?', [$manual_id]);
dd($query);

Error HTTP 500 Internal Server Error

Call to a member function value() on array

Of course, I can traverse the array to pull the value, but the whole point of using a method is to avoid such extra rigamarole.


Per a request in the comments, here is some sample data and expected result. First, the query:

MariaDB [dev]> SELECT MAX(sort) FROM man_pos WHERE manual_id = 1;
+-----------+
| MAX(sort) |
+-----------+
|         3 |
+-----------+

Second, what I would like to get:

$max_sort = DB::select('SELECT max(sort) AS sort FROM man_pos WHERE manual_id = ?', [$manual_id])->getSingleValue();

dd($max_sort);

^ 3
2
  • can you write sample data and expected data Commented Dec 1, 2020 at 5:28
  • @NurbekBoymurodov Please see edits Commented Dec 1, 2020 at 5:36

2 Answers 2

2

You may just try using Laravel's built in MAX function:

$max_sort = DB::table('man_pos')
    ->where('manual_id', $manual_id)
    ->max('sort');
Sign up to request clarification or add additional context in comments.

Comments

0

you want single column for single max return single value

$max_sort = DB::table('man_pos')->select('sort')->where('manual_id', '=', $manual_id)->max('sort');

1 Comment

@user151841 I just tested i was mistake you dont need get() and first() when you are using max() i edited answer did you try Tim Biegelesion answer it shoud be works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.