30

Can anyone please explain in detail what Eloquent's Model::query() means?

Shateel Ahmed
  • 1,264
  • 2
  • 12
  • 23

1 Answers1

72

Any time you're querying a Model in Eloquent, you're using the Eloquent Query Builder. Eloquent models pass calls to the query builder using magic methods (__call, __callStatic). Model::query() returns an instance of this query builder.

Therefore, since where() and other query calls are passed to the query builder:

Model::where()->get();

Is the same as:

Model::query()->where()->get();

Where I've found myself using Model::query() in the past is when I need to instantiate a query and then build up conditions based on request variables.

$query = Model::query();
if ($request->color) {
    $query->where('color', $request->color);
}
ruleboy21
  • 5,510
  • 4
  • 17
  • 34
Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95