Laravel Tutorials

Laravel Collection Pluck Method Gains Closure Transformation Power

Published
Laravel Collection Pluck Method Gains Closure Transformation Power image

Laravel's collection pluck() method now accepts closures for both key and value parameters, eliminating the need for verbose mapWithKeys() approaches when applying simple transformations during data extraction.

Previously, transforming data while plucking required abandoning the clean pluck() syntax in favor of more complex collection methods:

$locations = City::get()->mapWithKeys(function ($city) {
    return [$city->id => "{$city->country_code} - {$city->name}"];
});

The enhanced pluck() method streamlines this process with closure support:

$locations = City::get()
    ->pluck(fn ($city) => "{$city->country_code} - {$city->name}", 'id');

Consider an inventory management system where product listings need formatted display values:

<?php

namespace App\Services;

use App\Models\Product;
use App\Models\Category;

class InventoryService
{
    public function getFormattedProducts()
    {
        $products = Product::with('category')->get()
            ->pluck(fn ($product) => "#{$product->sku} - {$product->name}", 'id');
        
        return $products;
    }

    public function getPricedInventory()
    {
        $inventory = Product::active()->get()
            ->pluck(fn ($product) => '$' . number_format($product->price, 2), 'sku');
        
        return $inventory;
    }

    public function getCategorizedItems()
    {
        $categories = Category::with('products')->get()
            ->pluck('name', fn ($category) => str_slug($category->name));
        
        return $categories;
    }
}

This approach works seamlessly in view contexts where formatted data is essential. Building select dropdowns becomes more straightforward:

$productOptions = Product::available()->get()
    ->pluck(fn ($product) => "{$product->brand} {$product->model}", 'id');
<select name="product_id" class="form-control">
    @foreach($productOptions as $id => $displayName)
        <option value="{{ $id }}">{{ $displayName }}</option>
    @endforeach
</select>

The closure support handles various transformation needs without requiring complex mapping operations. You can concatenate fields, apply formatting functions, add prefixes or suffixes, and create dynamic keys based on model properties. This maintains the familiar pluck() interface while providing the flexibility previously available only through more verbose collection methods.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article