0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel pluck

Last updated at Posted at 2025-12-10

Laravel pluck

Laravel pluckメソッドは、主にコレクションやEloquentクエリの結果に対して使用され、指定したキーの値だけを抜き出して新しい配列を生成できる

基本的な使い方
pluckメソッドは2つの引数を受け取る

  • $value:取得したい値のキー
  • $key:新しい配列のキーとして使用したいカラム名

値だけを抜き出す

コレクション内の全アイテムから、特的の一つのカラムの値だけを取り出したい場合

$users = collect([
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
    ['id' => 2, 'name' => 'Bob', 'role' => 'user'],
    ['id' => 3, 'name' => 'Charlie', 'role' => 'admin'],
]);

// ユーザーの名前だけを抜き出す
$names = $users->pluck('name');

 
キーと値のペアを抜き出す

指定したカラムを新しい配列のキーに、別のカラムを値にして連想配列を生成する場合

// ユーザーの ID をキーに、名前を値にする
$keyed_users = $users->pluck('name', 'id');

/* $keyed_usersの中身は:
[
    1 => 'Alice', // id がキー
    2 => 'Bob',
    3 => 'Charlie',
]

 
Elouquentクエリ

// データベースから、全ユーザーのIDをキー、名前を値とする連想配列を取得
$userList = App\Models\User::all()->pluck('name', 'id');
// または、コレクションを生成せずに直接実行する方が効率的です。
$userList = App\Models\User::pluck('name', 'id');
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?