Laravel Pluck() : Laravel Collection Method to extract values
By Parth Patel on Oct 04, 2020
Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection.
You might often would want to extract certain data from the collection i.e Eloquent collection. Basic way is to loop through collection and extract but Laravel Collection has powerful helper methods among which Pluck() method helps to achieve same very easily.
Let's review some of the use cases with examples:
Extract single column from Laravel Collection using Laravel Pluck()
Suppose you want to get email addresses from the Collection of users:
$emails = Users::pluck('email');
dd($emails);
//output
Illuminate\Support\Collection {#4526
all: [
"test@example.com",
"testuser@example.com",
],
}
Extract Multiple Columns in Key-Pair value form using Laravel Pluck()
Laravel Pluck() function also allows you to extract multiple columns in key-value form. This can be helpful in various usecases.
Let's review one example.
Support you want to get Name → Email data from Laravel collection of users:
$users = Users::pluck('name','email');
dd($users);
//output
Illuminate\Support\Collection {#4694
all: [
"test@example.com" => "Test Admin",
"testusers@example.com" => "Test User",
],
}
For key-pair value extraction, second argument is set as the key. In our example, I have passed "email" as second argument, thus email addresses are used as key while names are values.
Note: You cannot extract more than 2 columns from Laravel Collection via pluck() method. For that, you should use select() method
Extract Value from Relationship using Laravel Pluck()
Laravel Pluck() function not only helps in extracting data from primary model but also allows getting data from relationship models.
Let's get key→value pair of email address and userprofile's bio:
$users = Users::with('userprofile')->get()->pluck('userprofile.address','email');
//output
Illuminate\Support\Collection {#4621
all: [
"test@example.com" => "733 Oakdale Avenue",
"testusers@example.com" => "3745 Hewes Avenue",
],
}
Note: Notice here I am using get() to first retrive the relation data. Without get(), pluck won't have access to relation data, since we are eager loading relation via with(). If we join relation manually, then get() is not required and we can pluck directly. Check example below:
$users = Users::join('user_profiles','users.id','=','user_profiles.user_id')
->pluck('userprofile.address','email');
//output
Illuminate\Support\Collection {#4621
all: [
"test@example.com" => "733 Oakdale Avenue",
"testusers@example.com" => "3745 Hewes Avenue",
],
}
We have reviewed all the use-cases for plucking data from Laravel Collection. By the way, here we are using pluck() function on Eloquent Collection. Same way, it can be used on regular Laravel Collection as well.