If you have a collection of Models you can use:
$users->map->only('name', 'hobby');
// returns e.g.
// collect([
// new User(['name' => 'matt', 'hobby' => 'coding']),
// new User(['name' => 'tomo', 'hobby' => 'cooking']),
// ]);
This only works on Models because the only
method is only available on Models, not on other items you might have in a Collection.
For a generic, more robust solution that works with Collections of mixed object types, arrays, etc., you can use the pluckMany
macro I contributed to Spatie's laravel-collection-macros package:
$collection->pluckMany(['name', 'hobby']);
// returns e.g.
// collect([
// (object) ['name' => 'marco', 'hobby' => 'drinking'],
// (object) ['name' => 'belle', 'hobby' => 'cross-stitch'],
// ]);
For more details about pluckMany, see my blog post on How to pluck multiple items from a Laravel Collection