Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pluck together with first using Query builder

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

like image 805
Marcin Nabiałek Avatar asked Sep 26 '14 07:09

Marcin Nabiałek


People also ask

What is Pluck () in laravel?

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.

What is difference between eloquent and query builder?

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.

What is the use of pluck?

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.


1 Answers

Try this one:

$user =  User::pluck('name')->first();
echo $user;
like image 50
hamidreza samsami Avatar answered Sep 25 '22 10:09

hamidreza samsami