How to Use pluck in Eloquent: Laravel Quick Guide
In Laravel Eloquent, use
pluck to retrieve a single column's values from the database as a collection. You can call pluck('column_name') on a model query to get all values of that column, optionally specifying a key column with pluck('value', 'key').Syntax
The pluck method extracts values of a specific column from the database query results. It returns a collection of those values.
pluck('value'): Gets all values from thevaluecolumn.pluck('value', 'key'): Gets values from thevaluecolumn keyed by thekeycolumn.
php
Model::pluck('column'); Model::pluck('value_column', 'key_column');
Example
This example shows how to get all user emails and then get user emails keyed by their IDs using pluck.
php
<?php use App\Models\User; // Get all emails as a collection $emails = User::pluck('email'); // Get emails keyed by user id $emailsById = User::pluck('email', 'id'); // Output results print_r($emails->toArray()); print_r($emailsById->toArray());
Output
Array
(
[0] => user1@example.com
[1] => user2@example.com
[2] => user3@example.com
)
Array
(
[1] => user1@example.com
[2] => user2@example.com
[3] => user3@example.com
)
Common Pitfalls
Common mistakes when using pluck include:
- Expecting
pluckto return a model or full record instead of just column values. - Using
pluckwithout specifying the correct column name, leading to empty results. - Confusing
pluckwithselectorget, which return full models or collections of models.
php
<?php // Wrong: expecting full model $users = User::pluck('email'); // $users contains emails only, not User models // Right: get full models $users = User::select('id', 'email')->get();
Quick Reference
| Usage | Description |
|---|---|
| pluck('column') | Get all values of a single column as a collection |
| pluck('value', 'key') | Get values keyed by another column |
| pluck returns | A collection of values, not full models |
| Use with care | Ensure column names exist to avoid empty results |
Key Takeaways
Use pluck to quickly get values of a single column from Eloquent queries.
Pluck returns a collection of values, not full model instances.
You can specify a key column to get an associative collection.
Always verify column names to avoid empty or unexpected results.
For full models, use select or get instead of pluck.