W3docs

Best way to do a PHP switch with multiple values per case?

To get specific attributes from a Laravel Collection, you can use the pluck method.

How to Extract Specific Attributes from a Laravel Collection

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

Example of getting specific attributes from a Laravel Collection

<?php

$collection = collect([['name' => 'Alice', 'age' => 25], ['name' => 'Bob', 'age' => 30], ['name' => 'Charlie', 'age' => 35]]);

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

// $names will contain ['Alice', 'Bob', 'Charlie']

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can also pass a second argument to the pluck method to specify a different key for the values:

Example of getting specific attributes from a Laravel Collection by using "pluck" method

<?php

$collection = collect([['name' => 'Alice', 'age' => 25], ['name' => 'Bob', 'age' => 30], ['name' => 'Charlie', 'age' => 35]]);

$ages = $collection->pluck('age', 'name');

// $ages will contain ['Alice' => 25, 'Bob' => 30, 'Charlie' => 35]

You can also use the map method to iterate over the collection and return a new collection with the desired attributes. This can be useful if you need to perform additional processing on the attributes before returning them:

Example of getting specific attributes from a Laravel Collection by using "map" method

<?php

$collection = collect([['name' => 'Alice', 'age' => 25], ['name' => 'Bob', 'age' => 30], ['name' => 'Charlie', 'age' => 35]]);

$names = $collection->map(function ($item) {
  return $item['name'];
});

// $names will contain ['Alice', 'Bob', 'Charlie']