xxxxxxxxxx
$collection = collect([
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Bob', 'age' => 35]
]);
$result = $collection->pluck('name');
// Output: ['John', 'Jane', 'Bob']
xxxxxxxxxx
$users = User::all()->pluck('field_name');
//for keys instead of [User::all()->pluck('id');] use
$user_ids = User::all()->modelKeys();
xxxxxxxxxx
$array = [
['developer' => ['id' => 1, 'name' => 'Taylor']],
['developer' => ['id' => 2, 'name' => 'Abigail']],
];
$array = array_pluck($array, 'developer.name');
// ['Taylor', 'Abigail'];
xxxxxxxxxx
$array = array_pluck($array, 'developer.name', 'developer.id');
// [1 => 'Taylor', 2 => 'Abigail'];
xxxxxxxxxx
//Phuơng thức này khá hữu dụng trong một số trường hợp,
//dùng để lấy toàn bộ một field nào đó và trả về mảng chứa
//giá trị của tất cả các field đó.
//Thông thường mình hay dùng để lấy toàn bộ id có
//trong bản ghi để dùng trong các điều kiện whereIn.
$studentIds = $students->pluck('id'); //kết quả là 1 Collection chửa mảng các id của student
xxxxxxxxxx
$studentIds = $students->pluck('id'); //kết quả là 1 Collection chửa mảng các id của student