How to get only one column as one dimentional array in laravel 5.2 using eloquent?
I have tried:
$array = Word_relation::select('word_two')->where('word_one', $word_id)->get()->toArray();
but this one gives it as 2 dimentional array like:
array(2) {
[0]=>
array(1) {
["word_one"]=>
int(2)
}
[1]=>
array(1) {
["word_one"]=>
int(3)
}
}
but I want to get it as:
array(2) {
[0]=>2
[1]=>3
}
You can use the pluck
method:
Word_relation::where('word_one', $word_id)->pluck('word_two')->toArray();
For more info on what methods are available for using with collection, you can you can check out the Laravel Documentation.
If you receive multiple entries the correct method is called lists.
Word_relation::select('word_two')->where('word_one', $word_id)->lists('word_one')->toArray();
lists()
works fine by it self. Thank you.
lists()
is deprecated in Laravel Ver.5.2 and later, where pluck()
as in the tagged answer is the way.
That can be done in short as:
Model::pluck('column')
where model is the Model such as User
model & column as column name like id
if you do
User::pluck('id') // [1,2,3, ...]
& of course you can have any other clauses like where
clause before pluck
I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().
// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();
These methods can also be called on a Collection for example
// <= Laravel 5.1
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->lists('word_one');
// >= Laravel 5.2
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->pluck('word_one');
I think you can achieve it by using the below code
Model::get(['ColumnName'])->toArray();
Model::get(['ColumnName'])->toArray();
is equivalent of doing Model::select('ColumnName')->get()->toArray()
which results in a multi dimensional array.
Success story sharing
select
being redundant, but I don't see a problem with having a collection as a result, because a collection is just a fancy array that can be iterated over the same as an array. I rarely use arrays instead of collections since the memory footprint is generally not a problem, and collections can be easily cast to arrays where needed because they implement thetoArray
method. However, for consistency with your question, I modified the answer to do convert the result.Collection
also has apluck()
method - What you are using is a method ofQueryBuilder
.