Get only specific attributes with from Laravel Collection

To get specific attributes from a Laravel Collection, you can use the pluck method. The pluck method retrieves all the values for a given key:

<?php

$collection = collect([['product_id' => 'prod-100', 'name' => 'desk'], ['product_id' => 'prod-200', 'name' => 'chair']]);

$names = $collection->pluck('name');

// $names will contain a new collection with ['desk', 'chair']

Watch a course Learn object oriented PHP

If you want to retrieve multiple attributes for each item in the collection, you can pass an array of keys to the pluck method:

<?php

$collection = collect([['product_id' => 'prod-100', 'name' => 'desk', 'price' => 100], ['product_id' => 'prod-200', 'name' => 'chair', 'price' => 50]]);

$products = $collection->pluck(['name', 'price']);

// $products will contain a new collection with [
//     ['name' => 'desk', 'price' => 100],
//     ['name' => 'chair', 'price' => 50],
// ]

You can also use the only method to retrieve a subset of the original collection containing only the specified keys:

<?php

$collection = collect([['product_id' => 'prod-100', 'name' => 'desk', 'price' => 100], ['product_id' => 'prod-200', 'name' => 'chair', 'price' => 50]]);

$subset = $collection->only(['name', 'price']);

// $subset will contain a new collection with [
//     ['product_id' => 'prod-100', 'name' => 'desk', 'price' => 100],
//     ['product_id' => 'prod-200', 'name' => 'chair', 'price' => 50],
// ]