2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Laravel】Collectionのpluckメソッド

Posted at

はじめに

今回もLaravelのCollectionのメソッドについてまとめたいと思います。

pluckメソッドで指定したキーの配列を取得する

例えば、nameの値のみをを取得する場合下記のような実装になります。

$collection = collect([
    ['id' => 1, 'name' => '山田', 'age' => 18],
    ['id' => 2, 'name' => '佐藤', 'age' => 38],
    ['id' => 3, 'name' => '小林', 'age' => 25],
]);

$names = $collection->pluck('name');

print_r($names->toArray());

実行結果は下記になります。

Array
(
    [0] => 山田
    [1] => 佐藤
    [2] => 小林
)

pluck('id', 'name')のようにidとnameなど複数指定するとその指定した値のみを配列にして取得することもできます。

おわりに

いかがでしたでしょうか。
指定したキーの配列を取得をして試してみてください。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?