What is the difference between uses User::all()
and User::get()
on Eloquent?
On Laravel API it describes only all()
on Eloquent\Model
.
Maybe get()
is described on Eloquent\Builder
.
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.
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
Avg method provided by Laravel Collection returns the average value. By default, it will provide average of all the values in collection.
When you are handling more data, it is better to use Laravel's DB facade query builder than Laravel's Eloquent ORM. From performance tests, inserting 1000 rows in a simple table takes Eloquent 1.2 seconds whereas the DB facade takes only 800 milliseconds.
User::all()
and User::get()
will do the exact same thing.
all()
is a static method on the Eloquent\Model
. All it does is create a new query object and call get()
on it. With all()
, you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters).
get()
is a method on the Eloquent\Builder
object. If you need to modify the query, such as adding a where clause, then you have to use get()
. For example, User::where('name', 'David')->get();
.
To further clarify why this works, it is because there is a magic method in the Model class which will take any static call that is not defined, create an instance, then call the method on the instance for you.
You can see it in the source code here: https://github.com/laravel/framework/blob/5.6/src/Illuminate/Database/Eloquent/Model.php (line 1580)
This is also explained in this Laracast episode: https://laracasts.com/series/advanced-eloquent/episodes/3 (Subscription required)
I too was mystified when I first came across this and couldn't find get()
as a static method. But then I recalled the Laracast episode which helped me connect the dots.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With