Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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'],
]
*/
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?