3

Here is my code:

$arr = Users::all()->toArray();

It returns an array of all table's columns. But I don't need to all columns. I need to return only these columns: 'id', 'name', 'email', 'age'. I've searched about that and I figured this out: (using pluck() function)

$arr = Users::pluck('id', 'name', 'email', 'age')->toArray();

But it doesn't return expected result. It returns this:

array:7 [▼
  "John" => 1
  "Peter" => 2
  "Jack" => 3
  "Ali" => 4
  "Teresco" => 5
  "Mark" => 6
  "Barman" => 7
]

As you see, there isn't email and age columns. How can I fix it?

Martin AJ
  • 6,261
  • 8
  • 53
  • 111

3 Answers3

4

You can do it using select method like this,

Users::select('id', 'name', 'email', 'age')
        ->get()
        ->toArray();
Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
1

You can collect arrays of columns in get() like this:

$arr = Users::get(array('id', 'name', 'email', 'age'))->toArray();
Martin AJ
  • 6,261
  • 8
  • 53
  • 111
S.I.
  • 3,250
  • 12
  • 48
  • 77
0

Try this:

Users::with(array('user'=>function($query){
        $query->select('id','username');
    }))->get();

It will only select id and username from other table. I hope this will help others.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59