Multiple Column Plucking in Laravel Collections


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.

The post Multiple Column Plucking in Laravel Collections appeared first on Laravel News.
Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.