Eloquent get only one column as an array


Php Problem Overview

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) {
      array(1) {
      array(1) {

but I want to get it as:

array(2) {

Php Solutions

Solution 1 - Php

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.

Solution 2 - Php

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();

Solution 3 - Php

That can be done in short as:


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

Solution 4 - Php

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');

Solution 5 - Php

I think you can achieve it by using the below code



All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRiiwoView Question on Stackoverflow
Solution 1 - PhpBogdanView Answer on Stackoverflow
Solution 2 - PhpmoxxView Answer on Stackoverflow
Solution 3 - PhpAPuView Answer on Stackoverflow
Solution 4 - PhpSamBremnerView Answer on Stackoverflow
Solution 5 - PhpsaeidView Answer on Stackoverflow