The new "select" method for Laravel Collections
Do you remember the only
method in Laravel Collections that allows you to retrieve a subset of the items from the collection?
For instance, if you have an array of data like so.
$collection = collect([
'name' => 'Amit',
'age' => 30,
'city' => 'Surat',
'country' => 'India'
]);
You can use the only
method to retrieve a subset of the items from the collection like so.
$filtered = $collection->only(['name', 'age']);
// ['name' => 'Amit', 'age' => 30]
Well, there’s a new method called select
in Laravel Collections that does the same thing as the only
method but for array of arrays.
For instance, if you have an array of arrays like so.
$collection = collect([
['name' => 'Amit', 'age' => 30, 'country' => 'India'],
['name' => 'John', 'age' => 25, 'country' => 'USA'],
['name' => 'Jane', 'age' => 35, 'country' => 'UK'],
]);
Now, if you want to retrieve a subset of the items, for example, name
and country
from the collection, you can use the select
method like so.
$filtered = $collection->select(['name', 'country']);
/*
[
['name' => 'Amit', 'country' => 'India'],
['name' => 'John', 'country' => 'USA'],
['name' => 'Jane', 'country' => 'UK'],
]
*/
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.