46

In Laravel is it possible to select only one field and return that as a set/ array.

For example consider the model Foo which is linked to table foos which has field id, a, b, c.

Consider the following sample data:

(1, 10, 15, 20)
(1, 12, 15, 27)
(1, 17, 15, 27)
(1, 25, 16, 29)
(1, 28, 16, 40)

Now if I wanted to create a query that returns all the values of a where b is 15, I could do that like so:

Foo::select('a')->where('b', 15)->get();

However this will return an eloquent collection.

Instead how can I return instead an array like this:

[10, 12, 17]

3 Answers 3

118

Just use pluck() and ->toArray():

Foo::where('b', 15)->pluck('a')->toArray();

Laravel's pluck() method.

Laravel's toArray() method.

Sign up to request clarification or add additional context in comments.

4 Comments

but dosen't that return an associative array?
Yes you have to use pluck() to select one specific column. I edited my answer
Just tried it and it works the way you want with pluck (or lists because lists() is an alias of pluck()) and toArray()
new knowledge to me..tq :)
5

The lists method is deprecated and pluck need some parameter so, if you want to get all the attributed in array format, use it this way.

Foo::select('a')->where('b', 15)->get()->all();

1 Comment

Foo::where('b', 15)->pluck('a')->all();
4

Do

Foo::where('b', 15)->lists('a')->all();

This will give you an array of ids. eg [2, 3, 5]

6 Comments

what does lists and all mean
lists will convert the result to a collection and all will make it an array. but with laravel 4 you can only use lists and it will convert your result to an array.
so can't i also write Foo::select('a')->where('b', 15)->all(); `
No. With what you want you can't use select and all. You will get a collection instead. but if you change the all to get()->toArray() you will get an associative array. So the best is to use lists and all
@YahyaUddin The lists method is just an alias for pluck as @Mushr00m very well exemplified in his answer. The Laravel Documentation explains clearly what methods a Collection offers and what they do.
|

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.