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

2019-03-17 04:15发布

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.

2条回答
\"骚年 ilove
2楼-- · 2019-03-17 04:51

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.

查看更多
Lonely孤独者°
3楼-- · 2019-03-17 04:52

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

查看更多
登录 后发表回答