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'],
]
*/
👋 Hi there! I'm Amit. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!