Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] 
like image 590
Yahya Uddin Avatar asked Mar 08 '16 01:03

Yahya Uddin


People also ask

What does toArray do in laravel?

all() will return you Eloquent Objects where as toArray() will return you Associative Arrays.

What is difference between Pluck and select in laravel?

Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array. Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.

How to use collections in Laravel?

Creating Collections As mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as: $collection = collect([1, 2, 3]); The results of Eloquent queries are always returned as Collection instances.

What is collection and object in laravel?

Laravel collections allow you to work efficiently with arrays. Basically you take arrays as input and it will create Illuminate\Support\Collection object once you have the object available than you can perform different types of array operations on the object.


2 Answers

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

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

Laravel's pluck() method.

Laravel's toArray() method.

like image 163
Mushr00m Avatar answered Sep 29 '22 11:09

Mushr00m


Do

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

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

like image 30
oseintow Avatar answered Sep 29 '22 09:09

oseintow