Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 509
Shateel Ahmed Avatar asked Jul 25 '18 10:07

Shateel Ahmed


People also ask

What is query () in Laravel?

In Laravel the database query builder provides an easy interface to create and run database queries. It can be used to perform all the database operations in your application, from basic DB Connection, CRUD, Aggregates, etc. and it works on all supported database systems like a champ.

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

What is Laravel eloquent query?

Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table.

What is first () in Laravel?

The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.


1 Answers

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

Hope this example helps.

like image 117
Devon Avatar answered Sep 21 '22 13:09

Devon