How to Pluck Multiple Columns Using Laravel Collections

Laravel devs, here's a gem for you: 💎 Did you know you can pluck multiple values in Laravel? Use the map method to extract multiple columns from a collection efficiently! In this blog post, we'll explore how to achieve this and why it’s beneficial for your Laravel applications.

What is Pluck?

The pluck() method in Laravel is a convenient way to extract a single column's values from a collection or an array. It’s commonly used to retrieve values like IDs, names, or other attributes from an array of data. However, the pluck() method natively supports only a single column or key-value pair extraction. To extract multiple columns, we need to use a different approach.

Using map to Pluck Multiple Columns

To pluck multiple columns, we can leverage the map method in combination with only. This allows us to specify and extract multiple columns efficiently from a collection. Here’s how to do it:

  1. Create a Model and Migration

Let’s create a Post model with a corresponding migration to have some data to work with:

php artisan make:model Post -m

Update the migration file to include the columns we need:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('description');
        $table->text('excerpt');
        $table->string('slug');
        $table->timestamps();
    });
}

Run the migration:

php artisan migrate
  1. Seed the Database

Add some dummy data to the posts table by creating a seeder:

php artisan make:seeder PostSeeder

In PostSeeder.php, add:

use Illuminate\Database\Seeder;
use App\Models\Post;

class PostSeeder extends Seeder
{
    public function run()
    {
        Post::create([
            'title' => 'First Post',
            'description' => 'Description of the first post',
            'excerpt' => 'First post excerpt',
            'slug' => 'first-post',
        ]);

        Post::create([
            'title' => 'Second Post',
            'description' => 'Description of the second post',
            'excerpt' => 'Second post excerpt',
            'slug' => 'second-post',
        ]);
    }
}
  1. Pluck Multiple Columns Using map

Now, let’s use the map method to pluck multiple columns from the posts collection:

use App\Models\Post;

Route::get('/pluck-multiple', function () {
    $posts = Post::all()->map->only(['title', 'description', 'excerpt', 'slug']);
    return $posts;
});
  1. In this example, we are defining a route that retrieves all posts from the database, then uses the map method to pluck only the specified columns (title, description, excerpt, and slug). This returns a collection containing only the specified columns for each post.

Example Output

When you visit the /pluck-multiple route, the output will be a JSON representation of the posts with only the specified columns:

[
    {
        "title": "First Post",
        "description": "Description of the first post",
        "excerpt": "First post excerpt",
        "slug": "first-post"
    },
    {
        "title": "Second Post",
        "description": "Description of the second post",
        "excerpt": "Second post excerpt",
        "slug": "second-post"
    }
]

Found this helpful?

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe