Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

【Laravel】DB登録値取得時のfind()、get()、first()の返り値早見表

More than 1 year has passed since last update.

よく忘れるのでメモ

find()

App\Model::find(1) の返り値はModelのオブジェクト

get()

App\Model::where('id',1)->get() の返り値はCollectionクラス
(中身はModelのオブジェクト。ゆえにforeach()で回せば各々の値を取得できる。)

first()

App\Model::where('id',1)->first() の返り値はModelのオブジェクト

※もしなかった場合はNULLを返す

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

$ php artisan tinker
New version is available (current: v0.8.14, latest: v0.8.15)
>>> App\Model::find(1)
=> App\Model{#458
     id: 1,
     name: "モデル1",
     created_at: "2017-11-30 07:32:29",
     updated_at: "2017-11-30 07:32:29",
   }

>>> App\Model::where('id',1)->get()
=> Illuminate\Database\Eloquent\Collection {#449
     all: [
       App\Model{#448
         id: 1,
         name: "モデル1",
         created_at: "2017-11-30 07:32:29",
         updated_at: "2017-11-30 07:32:29",
       },
     ],
   }

>>> App\Model::where('id',1)->first()
=> App\Model{#470
     id: 1,
     name: "モデル1",
     created_at: "2017-11-30 07:32:29",
     updated_at: "2017-11-30 07:32:29",
   }

>>>

ちなみに:where()

ちなみに

App\Model::where('id',1)の返り値はBuilderクラス

>>> App\Model::where('id',1)
=> Illuminate\Database\Eloquent\Builder {#462}
>>>

そんで:all()

そんでApp\Model::all() の返り値はCollectionクラス

>>> App\Model::all()
=> Illuminate\Database\Eloquent\Collection

もっとくわしく

おわり

以下もどうぞ

sola-msr
ミセ*゚ー゚)リ そんな事言われてもウチ、ポン・デ・ライオンやし
andfactory
Smartphone Idea Companyとして、人々の生活に「&(アンド)」を届ける。
https://andfactory.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away