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

Solution 1:

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

Solution 2:

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.

Solution 3:

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