ChatGPT解决这个技术问题 Extra ChatGPT

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.


p
patricus

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


K
Kenny

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.


This is really a handy insight. I hadn't come across why that worked before. Laravel's magic under the hood can sometimes make you go "Huh?!"
Indeed! It’s one of the things that attracted me to it. 😊
H
Hedayatullah Sarwary

get() is used when you want to add queries and all() is used to get all data, without using any condition.

Example of all():

$query = Project::all();

Example of get():

$query = Project::select('id', 'name')->where('name', '')->orderBy('id', 'desc')->get();