user151841
user151841

Reputation: 18046

Getting a single value from DB::select in Laravel 7.x

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

Upvotes: 1

Views: 558

Answers (2)

Nurbek Boymurodov
Nurbek Boymurodov

Reputation: 542

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');

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

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

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

Upvotes: 2

Related Questions