0
0
LaravelHow-ToBeginner · 3 min read

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 the value column.
  • pluck('value', 'key'): Gets values from the value column keyed by the key column.
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 pluck to return a model or full record instead of just column values.
  • Using pluck without specifying the correct column name, leading to empty results.
  • Confusing pluck with select or get, 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

UsageDescription
pluck('column')Get all values of a single column as a collection
pluck('value', 'key')Get values keyed by another column
pluck returnsA collection of values, not full models
Use with careEnsure 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.