Laravel Eloquent VS DB Query Builder

Laravel Eloquent VS DB Query Builder

post-9.png

 

Eloquent or DB Query Builder? 

One common struggle for most of the PHP developers. Let go deep for this topic.
As developers, it is widely understood that working with DB Query Builder is a skill that is extensively familiar to most of us. So, what is Eloquent? Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. It provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table.
Here will be from few point of view to discuss about Eloquent and DB Query Builder.

 

First of all, there is no objection in the CRUD manner in Eloquent. We 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 alerts or update statistics counters when someone has created a new account), traits (timestamps, soft deletes, your custom traits) eager/lazy loading etc. Domain-driven pattern and implement some pieces of business logic in system (e.g. validation, managing relations, calculations etc) also can be apply by using this it.
We move on to the next point, clean and easy understanding code always the best practice when write the coding. It also make developer’s life easier since Eloquent have it own standard to code which make the whole system easy to be maintain.
Hard to imagine? Let see the example below:

Eloquent

9-1.png

DB Query Builder? 

9-2.png

I believe no further explanation needed, Eloquent definitely gain the upper hand after compared which raw query look more complicated.
So, what make you struggle so much between Eloquent and DB Query Builder? Answer is Performance Issue.

 

When process a single record or a few records, there is nothing to worry about. But when come to process lots of records, let say data grids, reporting or batch processing, performance is the significant concern for developers.

 

Use back the example above, DB query builder performed better than Eloquent to get records which it just consider as a very simple query. May be you will feel that the different is too little and negligible, but try to imagine when the data is up to 10000 or even more? Ya, you already have the answer for it. 

So in conclusion, Eloquent is just nice to use but when process heavy data, DB query builder will be a better choice.

Post Info

Category:

Tags:

Date:

24 Aug 2023
Blog

Related Post