If I want to get get name of first user in database using eloquent I can do something like that:
$user = User::select('name')->first()->pluck('name');
// or $user = User::first()->pluck('name');
echo $user;
to get only name of this user as string.
However If I try the same using only query builder:
$user = DB::table('users')->select('name')->first()->pluck('name');
echo $user;
I get exception:
Call to undefined method stdClass::pluck()
But without using first it will work:
$user = DB::table('users')->select('name')->where('id',1)->pluck('name');
echo $user;
Is it not possible to use pluck
with first
using query builder or am I doing something wrong?
PS. Of course I know that I can display any property using $user->name
without using pluck
but I'm just curious why using Eloquent it works and using Query Builder it works only when not having both first
and pluck
You don't want to use
pluck
withfirst
, because it's redundant:So use only
pluck
:It does all you need.
But there's more.
Under the hood
first
andpluck
run 2 separate queries, so:So it's not only redundant to use
first
beforepluck
, but also it causes unexpected results.You can chain those methods on Eloquent query, since it returns a collection (
get
) or model (first
), butQuery\Builder
returns just an array (get
) orstdObject
(first
). That's why you couldn't do the same oon the query builder.In Laravel 5.1+, you can use the
value
method.From the docs:
This is how it works behind the scenes in the Builder class:
Try this one:
To get first occurence, You can either use
or use,