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?
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.
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.
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.
Avg method provided by Laravel Collection returns the average value. By default, it will provide average of all the values in collection.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With