Similar to the Request only($keys) function, this allow to quickly clean an Eloquent Collection and return an array containing th items with only the keys selected
Example:
dd($myCollection);
object(Illuminate\Database\Eloquent\Collection)
protected 'items' =>
array
0 =>
object(Model)
.......
protected 'attributes' =>
array
'id' => int 1
'name' => string 'myName1'
'option' => string 'myOption1'
.......
1 =>
object(Model)
.......
protected 'attributes' =>
array
'id' => int 2
'name' => string 'myName2'
'option' => string 'myOption2'
.......
$filteredArray = $myCollection->only('id', 'name')
dd($filteredArray);
array
0 =>
array (size=3)
'id' => int 1
'name' => string 'myName1'
1 =>
array (size=3)
'id' => int 2
'name' => string 'myName2'
can PR for this
I don't think this would be needed in the core.
You could use Laravel's array_pluck() method potentially.
Another solution would be simply be:
$filtered = $collection->map(function($value)
{
$wanted = ['id', 'name'];
return array_intersect_key(array_flip($wanted), $value);
});
Another approach to return specific keys would be:
$filtered = $collection->map(function($value)
{
extract($value);
return compact('id', 'name');
});
@bencorlett the first method is exactly what array_only does.
@bencorlett I know solutions like that exists, but I have to say that
$collection->only('id', 'name');
is a lot cleaner that your solutions...
and I think that almost all other Core Collection functions can be replaced by solution like yours...
I understand what you're saying. I'm basically trying to play devil's advocate.
How often do you see that being used?
What happens if somebody else has a unique use-case? Should their function be put in the core?
To be honest, on further analysis, I don't see too much wrong with this, it's just all good additions should be able to stand some scrutiny to justify their need.
Sent from my iPhone
Please excuse my brevity
On 4 Feb 2014, at 12:42 am, Elyahou [email protected] wrote:
@bencorlett I know solutions like that exists, but I have to say that
$collection->only('id'), 'name') is a lot cleaner that your solutions...
and I think that almost all other Core Collection functions can be replaced by solution like yours...
—
Reply to this email directly or view it on GitHub.
This has been implemented.
Works a little differently though.
where is the implementation ?
Last commit on the 4.1 branch: https://github.com/laravel/framework/commit/a084f61690d10a58645a28ebf835809bd6aae99f
Thanks.
"Works a little differently though.", I would rather say, nothing to do with what I proposed... :)
But I understand that the Collection class only manage a collection of items and dont have to deal with the items values
Most helpful comment
Thanks.
"Works a little differently though.", I would rather say, nothing to do with what I proposed... :)