Reputation: 1929
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
}
Upvotes: 148
Views: 238732
Reputation: 47
In Laravel 5.2, you can retrieve a single column as a one-dimensional array from a database using Eloquent by using the pluck method. The pluck method retrieves a collection of a single column's values. Here's an example of how you can use it:
1- Basic Usage of pluck Method:
$columnValues = YourModel::pluck('columnName')->all();
In this example, replace YourModel with the name of your Eloquent model and columnName with the name of the column you want to retrieve. The all() method is used to convert the collection into a plain PHP array.
2- Applying Conditions: You can also apply conditions before plucking the values. For instance, if you want to get values of a column where another column meets a certain condition, you can do:
$columnValues = YourModel::where('anotherColumnName', 'value')->pluck('columnName')->all();
This will first filter the rows where anotherColumnName equals value and then pluck the values of columnName.
Upvotes: -4
Reputation: 1250
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
Upvotes: 21
Reputation: 823
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');
Upvotes: 9
Reputation: 189
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();
Upvotes: 16
Reputation: 44526
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.
Upvotes: 284