Laravel 5.2 pluck() multiple attributes from Eloquent Model Collection

Fusion picture Fusion · May 10, 2016 · Viewed 34.6k times · Source

Laravel 5.2 has pretty nice Helpers, I would like to use them to do following:

I have Eloquent Model Collection:

$lesson->users(); // returns Eloquent collection of 3 users

pluck() function would be useful, but it can get just single parameter. However I want to get output with two parameters, id and name, like this:

[
1=>['id'=>10,'name'=>'Michael Dook'],
2=>['id'=>16,'name'=>'Henry Babcock'],
3=>['id'=>19,'name'=>'Joe Nedd']
]

Is there any elegant solution for this?

Answer

Blake picture Blake · Sep 1, 2016

I know this isn't the most recent question, but in case someone stumbles onto it from google later, see the Only Collection Method

$lesson->users()->only("id", "name")->toArray(); should be what you're after.