Laravel / PHP: pluck
Glossary overview

Laravel / PHP: pluck

В Laravel (и вообще в PHP через коллекции Eloquent) метод pluck() используется, чтобы достать одно конкретное поле из набора моделей и получить простой массив (или коллекцию) значений этого поля.

Например, я получаю все Tags.

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        Category::factory(10)->create();
        $tags = Tag::factory(10)->create();
        $posts = Post::factory(50)->create();

        dd($tags);
.....
Illuminate\Database\Eloquent\Collection {#1787
  #items: array:10 [
    0 => App\Models\Tag {#1783
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: true
      #escapeWhenCastingToString: false
      #attributes: array:4 [
        "title" => "Error"
        "updated_at" => "2025-11-04 13:30:18"
        "created_at" => "2025-11-04 13:30:18"
        "id" => 11
      ]
      #original: array:4 [
        "title" => "Error"
        "updated_at" => "2025-11-04 13:30:18"
        "created_at" => "2025-11-04 13:30:18"
        "id" => 11
      ]
      #changes: []
      #previous: []
      #casts: []
      #classCastCache: []
      #attributeCastCache: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      #relationAutoloadCallback: null
      #relationAutoloadContext: null
      +timestamps: true
      +usesUniqueIds: false
      #hidden: []
      #visible: []
      #fillable: array:1 [
        0 => "title"
      ]
      #guarded: array:1 [
        0 => "*"
      ]
    }
    1 => App\Models\Tag {#1784
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: true
      #escapeWhenCastingToString: false
      #attributes: array:4 [
        "title" => "Architecto"
        "updated_at" => "2025-11-04 13:30:18"
        "created_at" => "2025-11-04 13:30:18"
        "id" => 12
      ]
      #original: array:4 [
        "title" => "Architecto"
        "updated_at" => "2025-11-04 13:30:18"
        "created_at" => "2025-11-04 13:30:18"
        "id" => 12
      ]
      #changes: []
      #previous: []
      #casts: []
      #classCastCache: []
      #attributeCastCache: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      #relationAutoloadCallback: null
      #relationAutoloadContext: null
      +timestamps: true
      +usesUniqueIds: false
      #hidden: []
      #visible: []
      #fillable: array:1 [
        0 => "title"
      ]
      #guarded: array:1 [
        0 => "*"
      ]
    }
    2 => App\Models\Tag {#1782
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: true
      #escapeWhenCastingToString: false
      #attributes: array:4 [
        "title" => "Ipsam"
        "updated_at" => "2025-11-04 13:30:18"
        "created_at" => "2025-11-04 13:30:18"
        "id" => 13
      ]
      #original: array:4 [
        "title" => "Ipsam"
        "updated_at" => "2025-11-04 13:30:18"
        "created_at" => "2025-11-04 13:30:18"
        "id" => 13
      ]
      #changes: []
      #previous: []
      #casts: []
      #classCastCache: []
      #attributeCastCache: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      #relationAutoloadCallback: null
      #relationAutoloadContext: null
      +timestamps: true
      +usesUniqueIds: false
      #hidden: []
      #visible: []
      #fillable: array:1 [
        0 => "title"
      ]
      #guarded: array:1 [
        0 => "*"
      ]
    }
    3 => App\Models\Tag {#1781
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: true
      #escapeWhenCastingToString: false
      #attributes: array:4 [
        "title" => "Magni"
        "updated_at" => "2025-11-04 13:30:18"
        "created_at" => "2025-11-04 13:30:18"
        "id" => 14
      ]
      #original: array:4 [
        "title" => "Magni"
        "updated_at" => "2025-11-04 13:30:18"
        "created_at" => "2025-11-04 13:30:18"
        "id" => 14
      ]

Сейчас мы получаем просто коллекцию из объектов Tag.

А мы хотим только получить id.

 public function run(): void
    {
        Category::factory(10)->create();
        $tags = Tag::factory(10)->create();
        $posts = Post::factory(50)->create();

        foreach ($posts as $post) {
            $tagsIds = $tags->pluck('id');
            dd($tagsIds);
            $post->tags()->sync($tagsIds);
        }
    }

Получили ids.

Illuminate\Support\Collection {#611
  #items: array:10 [
    0 => 21
    1 => 22
    2 => 23
    3 => 24
    4 => 25
    5 => 26
    6 => 27
    7 => 28
    8 => 29
    9 => 30
  ]
  #escapeWhenCastingToString: false
} 

Можем дальше получить рандомные несколько значений из этих ids.

foreach ($posts as $post) {
            $tagsIds = $tags->pluck('id')->random(3);
            dd($tagsIds);
            $post->tags()->sync($tagsIds);
        }

// Output
Illuminate\Support\Collection {#613
  #items: array:3 [
    0 => 35
    1 => 36
    2 => 38
  ]
  #escapeWhenCastingToString: false
} 

💡 Важно

  • pluck() можно вызывать на коллекции (результате Model::all(), ->get() и т.д.).
  • Он возвращает новую коллекцию, а не изменяет исходную.
  • Если хочешь получить именно массив, можешь добавить ->toArray():