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]
all() will return you Eloquent Objects where as toArray() will return you Associative Arrays.
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.
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.
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.
Just use pluck()
and ->toArray()
:
Foo::where('b', 15)->pluck('a')->toArray();
Laravel's pluck() method.
Laravel's toArray() method.
Do
Foo::where('b', 15)->lists('a')->all();
This will give you an array of ids. eg [2, 3, 5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With