Laravel - What's the benefit of calling query() method on an Eloquent model

Viewed 176

In the course "Eloquent Performance Patterns" by Jonathan Reinink I've seen him calling query() method on his Eloquent models before writing the actual query. Let me give an example:

User::query()
    ->with('company')
    ->paginate()

As far as I know, he could write:

User::with('company')
    ->paginate()

I've seen this practice over and over in his course. It raised a question in my head: Is there any benefit in doing so or is it just a personal preference?

1 Answers

There is no difference, you don't have to add query(). It was practical to instantiate the query for the cases similar to this;

$user = User::query();
        
if (true) { // check some condition and append query condition(s)
    $user->with('company');
}
        
return $user->paginate();

but then when method came and it became easier to do that;

return User::query()
    ->when(true, function (Builder $builder) {
        $builder->with('company');
    })
    ->paginate();
Related