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
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();