Laravel Tutorials

Multiple Column Plucking in Laravel Collections

Published Updated
Multiple Column Plucking in Laravel Collections image

Laravel provides an efficient way to extract multiple column values from collections using the map method. While pluck() is limited to single columns, combining map with only allows for more flexible data extraction.

Understanding map with only

The map method combined with the only method enables extracting multiple specific columns from collections efficiently. Here's how to implement it:

<?php
	
namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function list()
    {
        return Article::take(20)->get()->map->only([
            'title',
            'content',
            'summary',
            'url_path'
        ]);
    }
}

Let's create a practical example with an article management system:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->text('summary');
            $table->string('url_path');
            $table->timestamps();
        });
    }
};

// ArticleSeeder.php
use App\Models\Article;

class ArticleSeeder extends Seeder
{
    public function run()
    {
        Article::create([
            'title' => 'Getting Started',
            'content' => 'Full article content here...',
            'summary' => 'Quick guide to get started',
            'url_path' => 'getting-started'
        ]);

        Article::create([
            'title' => 'Advanced Topics',
            'content' => 'Advanced content here...',
            'summary' => 'Deep dive into features',
            'url_path' => 'advanced-topics'
        ]);
    }
}

The API response will contain only the specified fields:

[
    {
        "title": "Getting Started",
        "content": "Full article content here...",
        "summary": "Quick guide to get started",
        "url_path": "getting-started"
    },
    {
        "title": "Advanced Topics",
        "content": "Advanced content here...",
        "summary": "Deep dive into features",
        "url_path": "advanced-topics"
    }
]

Map with only provides a clean, efficient way to extract multiple columns from your Laravel collections, streamlining data transformation while maintaining readable and maintainable code.

Harris Raftopoulos photo

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

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

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