Yahya Uddin
Yahya Uddin

Reputation: 28841

How to return Eloquent models' single column values as an array

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]

Upvotes: 45

Views: 118223

Answers (3)

Moeen Basra
Moeen Basra

Reputation: 771

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

Upvotes: 5

Mushr00m
Mushr00m

Reputation: 2356

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

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

Laravel's pluck() method.

Laravel's toArray() method.

Upvotes: 117

oseintow
oseintow

Reputation: 7371

Do

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

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

Upvotes: 4

Related Questions