44

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]
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

3 Answers3

114

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

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

Laravel's pluck() method.

Laravel's toArray() method.

Okihita
  • 167
  • 1
  • 11
Mushr00m
  • 2,258
  • 1
  • 21
  • 30
4

Do

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

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

oseintow
  • 7,221
  • 3
  • 26
  • 31
  • what does `lists` and `all` mean – Yahya Uddin Mar 08 '16 at 01:55
  • **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. – oseintow Mar 08 '16 at 02:01
  • so can't i also write `Foo::select('a')->where('b', 15)->all();` ` – Yahya Uddin Mar 08 '16 at 02:09
  • 1
    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** – oseintow Mar 08 '16 at 02:11
  • 1
    @YahyaUddin The `lists` method is just an alias for [`pluck`](https://laravel.com/docs/5.2/collections#method-pluck) as @Mushr00m very well exemplified in his answer. The Laravel Documentation explains clearly [what methods a Collection offers](https://laravel.com/docs/5.2/collections#available-methods) and what they do. – Bogdan Mar 08 '16 at 02:14
  • You shouldn't use lists anymore as a it's depricated and will be removed in future versions, use pluck() instead. – Alexey Mezenin Mar 08 '16 at 03:21
4

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();

Moeen Basra
  • 733
  • 4
  • 18