📅  最后修改于: 2023-12-03 15:02:35.460000             🧑  作者: Mango
Laravel Pluck is a useful method for extracting a list of specific values from a collection or array. It can help you quickly extract the values you need without having to loop through the entire collection. In this article, we will cover how to use Laravel Pluck in PHP.
$collection->pluck('column');
The pluck
method takes a single argument, which is the column or key from which you want to extract the value. This method returns a new collection containing the extracted values.
$users = App\Models\User::all();
$nameList = $users->pluck('name');
dd($nameList);
In this example, we use pluck
to extract the name
column from the users
collection. The resulting $nameList
collection will contain all the user names.
$users = [
[
'id' => 1,
'name' => 'John Doe',
'email' => 'johndoe@test.com',
'location' => [
'city' => 'New York',
'state' => 'NY',
],
],
[
'id' => 2,
'name' => 'Jane Doe',
'email' => 'janedoe@test.com',
'location' => [
'city' => 'Los Angeles',
'state' => 'CA',
],
],
];
$locations = collect($users)->pluck('location.city');
dd($locations);
If you have a multidimensional array, you can use the pluck
method to extract specific values from nested arrays. In this example, we extract the city
values from the location
array for each user.
Laravel Pluck is a useful method for extracting specific values from a collection or array. It can help you simplify your code and make it more efficient. We hope this article has been helpful and has given you a better understanding of how to use Laravel Pluck in PHP.