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
Since the find()
function will always use the primary key for the table, the need for get()
is not necessary. Because you can't narrow your selection down and that's why it will always just try to get that record and return it.
But when you're using the Fluent Query Builder you can nest conditions as such:
$userQuery = DB::table('users');
$userQuery->where('email', '=', 'foo@bar.com');
$userQuery->or_where('email', '=', 'bar@foo.com');
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get()
function.
// Done with building the query
$users = $userQuery->get();
find(n)
, you retrieve a row based on the primary key which is 'n'.first()
, you retrieve the first row among all rows that fit the where clauses.get()
, you retrieve all the rows that fit the where clauses. (Please note that loops are required to access all the rows or you will get some errors).find
returns one row from the database and represent it as a fluent / eloquent object. e.g. SELECT * FROM users WHERE id = 3
is equivalent to DB::table('users')->find(3);
get
returns an array of objects. e.g. SELECT * FROM users WHERE created_at > '2014-10-12'
is equivalent to DB::table('users')->where('created_at', '>', '2014-10-12')->get()
will return an array of objects containing users where the created at field is newer than 4014-10-12.
Basically what you need to understand is that get() return a collection(note that one object can be in the collection but it still a collection) why first() returns the first object from the result of the query(that is it returns an object) #Take_away Get() return a collection first() return an object
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();