Coder Perfect

As an array, Eloquent only accepts one column.

Problem

In Laravel 5.2, how can I get only one column as a one-dimensional array?

I have tried:

$array = Word_relation::select('word_two')->where('word_one', $word_id)->get()->toArray();

This one, on the other hand, offers it as a two-dimensional array, as follows:

array(2) {
      [0]=>
      array(1) {
        ["word_one"]=>
        int(2)
      }
      [1]=>
      array(1) {
        ["word_one"]=>
        int(3)
      }
    }

However, I’d like to have it as:

array(2) {
    [0]=>2
    [1]=>3
}

Asked by Riiwo

Solution #1

The pluck approach can be used:

Word_relation::where('word_one', $word_id)->pluck('word_two')->toArray();

Check out the Laravel documentation for further information on what methods are available for use with collections.

Answered by Bogdan

Solution #2

If you have several entries, you should use the list approach.

    Word_relation::select('word_two')->where('word_one', $word_id)->lists('word_one')->toArray();

Answered by moxx

Solution #3

In a nutshell, this can be done as follows:

Model::pluck('column')

where model refers to a model, such as the User model, and column refers to a column name, such as id.

if you do

User::pluck('id') // [1,2,3, ...]

&, of course, you can include any other clauses you want, such as a where clause before plucking.

Answered by APu

Solution #4

I came across this topic and thought I’d explain that in Laravel 5.2, the lists() method of an eloquent builder object was deprecated and pluck was introduced ().

// <= 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, for example, can be invoked on a Collection.

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

Answered by SamBremner

Solution #5

I believe you can do it with the code below.

Model::get([‘ColumnName’])->toArray();

Answered by saeid

Post is based on https://stackoverflow.com/questions/34912265/eloquent-get-only-one-column-as-an-array