Laravel - When to use ->get()

后端 未结 5 1912
悲哀的现实
悲哀的现实 2021-02-07 03:06

I\'m confused as to when ->get() in Laravel...

E.G. DB::table(\'users\')->find(1) doesn\'t need ->get() to retrieve the results, neither

5条回答
  •  鱼传尺愫
    2021-02-07 03:32

    The get() method will give you all the values from the database that meet your parameters where as first() gets you just the first result. You use find() and findOrFail() when you are searching for a key. This is how I use them:

    When I want all data from a table I use the all() method

    Model::all();
    

    When I want to find by the primary key:

      Model::find(1)->first();
    

    Or

     Model::findOrFail(1)->first();
    

    This will work if there is a row with a primary key of one. It should only retrieve one row so I use first() instead of get(). Remember if you deleted the row that used key 1, or don't have data in your table, your find(1) will fail.

    When I am looking for specific data as in a where clause:

    Model::where('field', '=', 'value')->get();
    

    When I want only the first value of the data in the where clause.

    Model::where('field', '=', 'value')->first();
    

提交回复
热议问题