Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 pluck() multiple attributes from Eloquent Model Collection

Tags:

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?

like image 315
Fusion Avatar asked May 10 '16 14:05

Fusion


People also ask

How do you pluck in Laravel eloquent?

While developing in eloquent, the column name can be passed as an argument in order to extract the values. Pluck () also accepts a second argument and if it happens to be an Eloquent collection, it will be another column name. To further strengthen the pluck() function, the wherein() function can be used.

What is Pluck () in Laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

What is difference between Pluck and select in Laravel?

Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array. Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.

Which of the following methods on collection will get all the records from it Laravel?

Avg method provided by Laravel Collection returns the average value. By default, it will provide average of all the values in collection.


2 Answers

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.

like image 191
Blake Avatar answered Sep 24 '22 21:09

Blake


Laravel: 5.7

if method is returning relation

use get()

e.g

$lesson = Lesson::find(1); $lesson->users()->get(['id', 'name']); 

on collections

use only()

$user = collect(['id' => 1, 'name' => 'Foo', 'role' => 'A']); $user->only(['id', 'name']); 

multiple arrays

$users = collect([     ['id' => 1, 'name' => 'Foo', 'role' => 'A'],     ['id' => 2, 'name' => 'Bar', 'role' => 'B']; ]);  $result = $users->map(function($user){    return Arr::only($user, ['id', 'name']); });  var_dump($result); 
like image 20
f_i Avatar answered Sep 25 '22 21:09

f_i