Tag Archives: Eloquent

Laravel Eloquent vs Query Builder

Eloquent Models

Eloquent is Laravel’s implementation of Active Record pattern for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. and it comes with all its strengths and weaknesses. It is a good solution to use when you process a single entity in a CRUD manner – that is, read from database or create a new entity and then save it or delete. You will benefit a lot from Eloquent’s features such as dirty checking (to send SQL UPDATE only for the fields which have been changed), model events (e.g. to send administrative alert or update statistics counter when someone has created a new account), traits (timestamps, soft deletes, custom traits) eager/lazy loading etc.

Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all. Also Eloquent has ton of extra features the the query builder lacks, such readability, accessors, mutators, JSON/Array conversion, hiding sensitive attributes, automatic timestamps, automatic attribute casting, softdeletes.

But, as you already know, it comes with some performance price. When you process a single or just a few records, there is nothing to worry about. But for cases when you read lots of records (e.g. for datagrids, for reports, for batch processing etc.) the plain DB is better approach.

Fluent query builder

Laravel’s database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.

The Laravel’s query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

NOTE: All methods available to Query Builder are available to Eloquent too, But method available to Eloquent Models is not available to Fluent, In short We can see Eloquent as a wrapper class over Query Builder.