Shoot down with the first use of Query builder

If I want to get the name of the first user in the database using eloquence, I can do something like this:

$user =  User::select('name')->first()->pluck('name');
// or $user =  User::first()->pluck('name');

echo $user;

to get only the name of this user as a string.

However, if I try to use the same query building method:

$user =  DB::table('users')->select('name')->first()->pluck('name');

echo $user;

I get an exception:

Call the undefined method stdClass :: pluck ()

But without using it, it will work first:

$user =  DB::table('users')->select('name')->where('id',1)->pluck('name');

echo $user;

Can't I use pluckwith firstusing the query builder or am I something wrong?

PS. Of course, I know that I can display any property with the help of $user->nameno use pluck, but I'm just wondering why using Eloquent works, and with the help of Query Builder it works only when it does not like first, andpluck

+5
4

pluck first, :

$query->first() // fetch first row
      ->pluck('name'); // fetch first row again and return only name

pluck:

$query->pluck('name');

, .


.

first pluck 2 , :

$query->where(..)->orderBy(..)->first() // apply where and orderBy
        ->pluck('name'); // no where and orderBy applied here!

, first pluck, .


Eloquent, (get) (first), Query\Builder (get) stdObject (first). .

+14

Laravel 5.1+ value.

:

, . :

$email = DB::table('users')->where('name', 'John')->value('email');

Builder:

/**
 * Get a single column value from the first result of a query.
 *
 * @param  string  $column
 * @return mixed
 */
public function value($column)
{
    $result = (array) $this->first([$column]);
    return count($result) > 0 ? reset($result) : null;
}
+3

:

$user =  User::pluck('name')->first();
echo $user;
+1

pluck() value().

,

  DB::table('users')->value('name');

,

 DB::table('users')->pluck('name')->first();
0

All Articles