How to return an array instead of a collection in Laravel?

In Laravel, you can select only one field and return it as a set / array.

For example, consider a model Foothat is associated with a table foosthat has a field id, a, b, c.

Consider the following data examples:

(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 a, where b- 15, I could do this:

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

However, this will return an eloquent collection.

Instead, how can I return an array this way:

[10, 12, 17]
+4
source share
3 answers

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

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

Laravel pluck().

Laravel toArray().

+13

, , , .

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

+1

Do

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

This will give you an array of identifiers. for example [2, 3, 5]

0
source

All Articles