If you have worked with Laravel, chances are you started straight away using Eloquent ORM and skipped over raw DB queries. However, you may have missed the coolness that is Fluent QueryBuilder. If you have done queries such as Model::where('name', 'John') you are somewhat used to the crazy awesome syntactic sugar that Fluent gives your code.

But, the rub comes through when we try to figure out what sort of magic dust Taylor and the core team put to make this dream come true. To start off, let's look back at the newQuery function in the Eloquent Model. In there, we kick off things by creating an Eloquent Query Builder. Then we setTable on the Query builder: this just takes our Model's getTable function and sets the table for our database connection. We also set the relationships base on our with attribute: we will look more into how the Query Builder loads relationships in a later post. Then we check whether we want to include or exclude soft-deleted models or not. If we need to exclude soft-deleted models, we add a query where the getQualifiedDeletedAtColumn which defaults to deleted_at.

Now, we have a Eloquent Query Builder instance to build off of. If you are familiar with the Fluent Query Builder, then you are able to run all of your normal queries mixed with Eloquent queries. But what is really cool is that the Eloquent Query Builder gives a lot of helper functions that allow for the crisp, fast ORM syntax that makes Eloquent great.


Find

Likely one of the first Eloquent query methods that you will learn is the find method, this grabs the models getKeyName and results in a query of where($primaryKey, '=', $id). Similarly, findOrFail runs the same query and if a model is not found, then a ModelNotFoundException is thrown.

This list will be updated slowly as time progresses and differences between the Eloquent Query Builder and the Fluent Query builder will be brought to light.

If you would like to look at the source of the Eloquent Query builder, check it out on Github