2

I want to make a query that gets all the users from table "users" and i need to have only user.id.

$users = User::all();

this will get the whole model User but this is a real performance issue for my app. There is too much data going through.

I need to append some data for each user so i can calculate the working hours.

So the question is how to fetch all users without any other data except $user->id?

4 Answers 4

2
$name = DB::table('users')->select('id')->get();
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't return the user model but only the id's from users. Almost same as pluck!
1

For the certain columns, I think this is best:

$users = User::select('id')->get();

See Documentation.

9 Comments

Code is tested and working fine, why down vote here???? Read carefully given link first.
how to fetch all users without any other data except $user->id, your code returns collection of User objects, test it.
@Addweb It seems some newbie have read bullcrap about strategic downvoting. Your code works just fine. Upvoted.
@patryk-uszynski Focus on OP's question part $user->id?. It does not mean that Object/Array...
@patryk-uszynski It's ok, ask to OP for you doubt from question.
|
0

Use the pluck() method:

$users = User::pluck('id');

The pluck method retrieves all of the values for a given key

6 Comments

Will this work with model? I thought pluck is helpler for collections
Yes it works, because Eloquent has pluck() method too.
this will only return the collection of all user->id...and then when i try to add some new property i get an error "Applying to non Object"
@lewis4u I thought you need only IDs. If you need to update multiple rows at once there is a better way to do that instead of getting collection of users and updating them one by one.
|
-1

Getting all User objects with id only:

$users = User::select('id')->get();

Getting all id as straight int value

According to documentation: https://laravel.com/docs/5.3/queries#selects

Specifying A Select Clause (most efficient)

$users = DB::table('users')->select('id')->get();

Retrieving A Single Column From A Row (but this will process all columns)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.