How to Use Pluck to Extract Certain Values from a Collection in Laravel

From WikiHTP

In Laravel, Illuminate\Support\Collection provides a fluent and convenient interface to deal with arrays of data. You may well have used these without knowing, for instance, Model queries that fetch multiple records return an instance of Illuminate\Support\Collection.

You will often find yourself with a collection of data where you are only interested in parts of the data.

In the example below we got a list of participants at an event and we want to provide a the tour guide with a simple list of names.

// First we collect the participants
$participants = collect([
    ['name' => 'John', 'age' => 55],
    ['name' => 'Melissa', 'age' => 18],
    ['name' => 'Bob', 'age' => 43],
    ['name' => 'Sara', 'age' => 18],
]);

// Then we ask the collection to fetch all the names
$namesList = $partcipants->pluck('name')
// ['John', 'Melissa', 'Bob', 'Sara'];

You can also use pluck for collections of objects or nested arrays/objects with dot notation.

$users = User::all(); // Returns Eloquent Collection of all users
$usernames = $users->pluck('username'); // Collection contains only user names

$users->load('profile'); // Load a relationship for all models in collection

// Using dot notation, we can traverse nested properties
$names = $users->pluck('profile.first_name'); // Get all first names from all user profiles

About This Tutorial

This page was last edited on 29 January 2019, at 18:52.