Search code examples
laraveleloquentlaravel-5.6laravel-query-builder

What is the meaning of Eloquent's Model::query()?


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


Solution

  • 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);
    }