Navigation

Laravel

How to Use `pluck()` to Create a Simple Array from a Collection

Extract specific values from Laravel collections using pluck(). Create simple arrays or key-value pairs from complex data structures efficiently.

Problem: You have a collection of objects or arrays and need to extract just one field into a simple array, or create a key-value array from two fields.

Solution:

// Basic pluck - extract single field
$users = User::all();
$names = $users->pluck('name');
// Result: ['John', 'Jane', 'Bob']

// Direct from query builder
$emails = User::pluck('email');
// Result: ['john@example.com', 'jane@example.com']

// Create key-value pairs
$userList = User::pluck('name', 'id');
// Result: [1 => 'John', 2 => 'Jane', 3 => 'Bob']

// Pluck nested values
$users = collect([
    ['name' => 'John', 'profile' => ['city' => 'NYC']],
    ['name' => 'Jane', 'profile' => ['city' => 'LA']]
]);
$cities = $users->pluck('profile.city');
// Result: ['NYC', 'LA']

// From relationships
$post = Post::with('comments')->first();
$commentTexts = $post->comments->pluck('text');

// Combine with other methods
$activeUserEmails = User::where('active', true)
    ->orderBy('name')
    ->pluck('email', 'id');

// For select dropdowns
$categories = Category::pluck('name', 'id');
// In Blade: {{ Form::select('category_id', $categories) }}

Why it works: pluck() extracts values from a specific key across all items in the collection. The second parameter becomes the key in the resulting array. It's more efficient than map() for simple extractions and works on both collections and query builders.

Performance tip: When used on query builder, pluck() only selects the specified columns from the database, making it very efficient.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel