Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Eloquent\Model::get() and all()

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.

like image 825
David Rodrigues Avatar asked Jan 04 '16 08:01

David Rodrigues


People also ask

What is get () in Laravel?

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.

What is an eloquent model?

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.

Which of the following methods on collection will get all the records from it Laravel?

Avg method provided by Laravel Collection returns the average value. By default, it will provide average of all the values in collection.

Is eloquent slower than query builder?

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.


2 Answers

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

like image 188
patricus Avatar answered Sep 19 '22 06:09

patricus


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.

like image 22
Kenny Avatar answered Sep 20 '22 06:09

Kenny