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

PhpLaravelLaravel 5Eloquent

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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 - Php

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 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid RodriguesView Question on Stackoverflow
Solution 1 - PhppatricusView Answer on Stackoverflow
Solution 2 - PhpKennyView Answer on Stackoverflow
Solution 3 - PhpHedayatullah SarwaryView Answer on Stackoverflow