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?

More than 1 year has passed since last update.

【Laravel】pluckメソッドを使ってみる

Posted at

pluckメソッドを使ってみる

開発をしていて、idがキーで特定のカラムをバリューとする配列を作りたくなることがある。
そんなときに使ってあげるのがpluck()メソッド。

pluck()

スクリーンショット 2023-01-12 21.49.04.png

実際の使い方(Laravel)

tinkerで見てみると下記のようにidがキーでpartカラムをバリューとした配列を作ることができています。

TrRecordController.
>>> TrPart::pluck('part_name', 'id');
=> Illuminate\Support\Collection {#4549
     all: [
       1 => "胸",
       2 => "脚",
       3 => "肩",
       4 => "背中",
       5 => "二頭",
       6 => "三頭",
       7 => "腹",
     ],
   }

引数はpluck('バリュー', 'キー')という順番で記載する必要があるので注意。

またこのような形でViewにわたすことができます。

create.blade.php
<div class="col-sm-10">
    <select class="form-control" id="menu_id" name="menu">
        <option value="" style="display: none;">選択してください</option>
        @foreach ($trMenus as $index => $name)
            <option value="{{ $index }}" {{ old('menu') === "$index" ? 'selected' : '' }} >{{ $name }}</option>
        @endforeach
    </select>
</div>

Collectionとか難しいですね。もっと勉強します(-_-)

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?