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
Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.
Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.
The pluck helper method is used to retrieve a list of specific values from a given $array. It is most useful when used against arrays of objects, but will also work with arrays just as well. You might often run into a situation where you have to extract certain value from a collection.
Try this one:
$user = User::pluck('name')->first();
echo $user;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With