Laravel

Laravel 10: pluck(): Extract Values with Laravel Collection Method

Laravel

Laravel 10: pluck(): Extract Values with Laravel Collection Method

Hello Laravel developers! In Laravel 10, the Collection class provides a powerful method called pluck(). This method allows you to extract specific values from a collection based on a given key. Let's explore how pluck() works and see some examples!

pluck() Method: 
The pluck() method retrieves all the values of a specified key from a collection. It returns a new collection containing only those values. Here's an example:

$users = collect([
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Alice', 'age' => 35],
]);

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

// Output: ['John', 'Jane', 'Alice']

In the above example, we have a collection of users. We use the pluck() method to extract the values of the 'name' key from each item in the collection. The resulting collection, $names, contains only the names of the users.

Additional Example: 
Here's another example demonstrating the use of pluck() with nested array structures:

$books = collect([
    [
        'title' => 'The Great Gatsby',
        'author' => [
            'name' => 'F. Scott Fitzgerald',
            'birth_year' => 1896,
        ],
    ],
    [
        'title' => 'To Kill a Mockingbird',
        'author' => [
            'name' => 'Harper Lee',
            'birth_year' => 1926,
        ],
    ],
    [
        'title' => 'Pride and Prejudice',
        'author' => [
            'name' => 'Jane Austen',
            'birth_year' => 1775,
        ],
    ],
]);

$authorNames = $books->pluck('author.name');

// Output: ['F. Scott Fitzgerald', 'Harper Lee', 'Jane Austen']

In this example, we have a collection of books, where each book has an 'author' array containing the author's name. We use pluck() to extract the author names from each book in the collection, resulting in a new collection, $authorNames, containing the names of the authors.

The pluck() method is a handy way to extract values from a collection based on a specific key. It simplifies data extraction and allows you to work with subsets of data from your collections.

That's it for today's Laravel tip!