Laravel offers a streamlined approach to retrieving multiple columns from collections using the map
method. Unlike pluck()
, which is limited to single columns, combining map
with only
provides enhanced flexibility for data extraction.
map
with only
The synergy between the map
and only
methods allows for efficient extraction of multiple specified columns from collections. Here's how to implement this technique:
<?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(fn($article) => $article->only([ 'title', 'content', 'summary', 'url_path' ])); } }
Let's illustrate this with an article management system example:
<?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; use Illuminate\Database\Seeder; 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 then only include 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" } ]
The map
and only
combination offers a concise and efficient method for selecting multiple columns from Laravel collections, resulting in cleaner, more maintainable code.
The above is the detailed content of Multiple Column Plucking in Laravel Collections. For more information, please follow other related articles on the PHP Chinese website!