📜  laravel collection pluck - PHP (1)

📅  最后修改于: 2023-12-03 15:32:33.039000             🧑  作者: Mango

Laravel Collection Pluck - PHP

Laravel Collection Pluck is a handy method in the Laravel PHP framework that allows developers to pluck specific values from a collection containing arrays or objects. In simpler terms, the pluck method can be used to extract specific fields from a collection and return them as a new collection.

Syntax

The syntax for using the pluck method in Laravel is straightforward. Here is an example:

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

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

// Returns [25, 30, 35]

As seen in this example, the pluck method is invoked on a collection containing arrays or objects. In this case, it extracts the 'age' field from each item in the collection and returns a new collection containing only the ages.

Multiple Values

Developers can also use the pluck method to extract multiple values from a collection. To do this, simply specify the keys of the array or object fields to extract as additional parameters to the pluck method. Here is an example:

$collection = collect([
    ['name' => 'John', 'age' => 25, 'gender' => 'Male'],
    ['name' => 'Jane', 'age' => 30, 'gender' => 'Female'],
    ['name' => 'Doe', 'age' => 35, 'gender' => 'Male']
]);

$data = $collection->pluck('name', 'gender');

// Returns ['Male' => 'John', 'Female' => 'Jane', 'Male' => 'Doe']

In this example, we pass two parameters to the pluck method: the first is the key of the field to extract ('name'), and the second is the key to use as the key of the resulting collection ('gender'). As a result, we get a new collection where the values of the 'name' field serve as the values, and the values of the 'gender' field become the keys.

Conclusion

Laravel Collection Pluck is a handy method that developers can use to extract specific values from a collection containing arrays or objects. With its straightforward syntax, it can easily be implemented in Laravel applications to simplify data processing and manipulation.