2 years agoby CMjeafar sadikh

Eloquent or querybuilder

which is best Eloquent or querybuilder


Sarthak replied 2 years ago


Both have their own advantage or disadvantages,

Words To Take Home

Simply: For normal CRUD based operation use Eloquent and for big query and dealing with lots of data, use QueryBuilder

Now lets go deeper.


Defined by laravel The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database.

It provides lots of quick functionality which normal query builder doest have.

  • Gives a fast CRUD based operation with very less code.
  • Can use eager/lazy load of relationships ( to load or not the relationship data )
  • Eloquent collection gives you more functions to alter your record in just a simple word.
  • Soft delete option ( data not deleted from database, just added an field of deleted_at to not show that data)
  • Dirty Checking ( update only whose fields which are changed )

Lets take comparision for eloquent is better

	// Eloquent query to find a user
	// Normal query

this is just an example of how easy is to use eloquent. there are tonnes of reason also.

But why there is querybuilder

Sometime for complex query, eloquent also doest work as expected, you have to get your core knowledge to do the task. Where you have much complex query then querybuilder comes in picture.

  • When you want to use Raw sql wuery then quiry builder is superb
  • If you are a master of join in tables and doest want to learn new things like Eloquent relationship or have your own way of joining table then use querybuilder.
  • Great option of using Pessimistic Locking
  • It is faster than eloquent for hundreds of data at once ( As I feel ).

Lets take comparision for Querybuilder is better

	// Eloquent query to enter 500 record takes almost 1.8 s
	// QueryBuilder to enter 500 record takes 892 ms

You can read more on Laravel documentation for Eloquent and QueryBuilder ( Just click the name )

Ask Question
Most Visited