Replies: 5 comments
-
Personally I think select feels most appropriate for this! |
Beta Was this translation helpful? Give feedback.
-
Certainly Filter gets better. |
Beta Was this translation helpful? Give feedback.
-
Attributes feels more natural |
Beta Was this translation helpful? Give feedback.
-
we can use this method: $people->map->only(['first', 'last', 'email']); |
Beta Was this translation helpful? Give feedback.
-
The discussion is pretty old so I don't know if it's fixed already but I'm using the following code (added it to the boot method in the AppServiceProvider.php) to mimic alternative 3: Collection::macro('columns', function ($columns) {
if (!is_array($columns)) {
$columns = [$columns];
}
return $this->map(function ($item) use ($columns) {
$newItem = [];
foreach ($columns as $column) {
if (array_key_exists($column, $item)) {
$newItem[$column] = $item[$column];
}
}
return $newItem;
});
}); |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I keep coming in situations where I want to filter out specific keys in a collection based on a multidimensional array.
I've previously made a PR, but it was a breaking change when extending the functionality of the
only
method. I'm sure this is a great addition to Collection, but I want to discuss the naming of the method.Alternative 1: Accept passing an array to
filter
In Pandas you can pass an array to the
filter
method and it will filter out the specific columns. I don't think this would be a breaking change, but would extend thefilter
method.Alternative 2: Accept passing an array to
map
When you have to do this manually you would use
map
to return a new collection with the keys you want. Passing an array to map wouldn't be a breaking change, but extend the functionality.Alternative 3: Add
columns
methodFollow the naming of the
array_column
method. I would suggest to usecolumns
instead ofcolumn
Alternative 4: Add
select
methodFollow the naming of Eloquent when selecting columns.
Alternative 5: Add
attributes
methodAlternative 6: Add
properties
methodSo what do you think? 💁♂️
filter
columns
select
attributes
properties
Update: Added
map
as an alternativeUpdate: Fixed typo in code example
Beta Was this translation helpful? Give feedback.
All reactions