3
3

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.

【Laravel5】テーブルのID全てを一次元配列の形で取得する

Last updated at Posted at 2019-07-05

テーブルのID全てを一次元配列の形で取得する

例としてここではusersテーブルのすべてのレコードのIDを一次元配列の形で取得します

pluck()を使用した例(ver.が5.2以降)

pluckメソッドは指定したキーの全コレクション値を取得します。

引用:コレクション 5.5 Laravel

pluck()でキーの全コレクションを取得したのちにtoArray()メソッドで配列にしてやると取得できます。
ということで以下のように記述

App\User::all()->pluck('id')->toArray();

以下tinker(laravel用REPL)で実行した際の様子

$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.4-1+ubuntu18.04.1+deb.sury.org+3 — cli) by Justin Hileman
>>> App\User::all()->pluck('id')->toArray()
=> [
     1,
     2,
     3,
     4,
     5,
     6,
   ]
>>>

lists()を使用した例(ver.が5.2以前)

もしLaravel5.2以前を使用している場合はlistsメソッドが使えるようです

App\User::where('id' ,'>' ,0)->lists('id')->toArray();

※手元に環境がないので動作は未確認

listsメソッドについて詳しくは以下を参照

【おまけ】バリデーションでテーブルにあるデータなのかをチェックする場合

例えば都道府県マスタ(prefecturesテーブル)にあるIDか否かをチェックする場合は以下のように記述すればいけるはず。
以下はUserRequestクラスにバリデーションルールを記述する際の例

UserRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            // ...
            'prefecture_id' => ['required', 'integer', Rule::in(Prefecture::all()->pluck('id')->toArray())],
        ];
    }

参考URL

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?