I have a basic query set up in the show method of a laravel resource
public function show($id){
$results = Student::find($id);
$drives= Drive:: where('student_id', $id);
}
The query for $results works perfectly. The query for $drives does not work unless I do ->get() at the end of it. Why is this? what's the difference between the two queries so that one requires the ->get() and the other does not? Solving this problem took me like 5 hrs and i'm just curious as to the functionality behind it so i can avoid this headache in the future.
Using the function
find()
on a model gets a query result based on the primary key of the model,id
in this case.When using
where()
, it gets a collection (an object of all query results), so if you only want the first result you must call$drives=Drive::where('student_id', $id)->first();
Here is a more in-depth explanation: the difference of find and get in Eloquent
use get to execute a builder query. unless you run the get() query wont be executed. get will return a collection.
1 - Use query builder to build queries however you want.
2 - when you are ready to execute the query call get()
If you want to get a single object by id use find, to get a single object
Some
eloquent
expressions have aget
implicitly. Those ones who are made by aQuery Builder
will need a->get()
call,find(), findOne()...
won't need aget()
.https://laravel.com/docs/5.6/eloquent#retrieving-models
https://laravel.com/docs/5.6/queries