Laravel offers two ways to work with your database:

  • Eloquent ORM. Eloquent provides an active record-based ORM. It provides a fluent interface with built-in relational capabilities.
  • Query Builder. The Query Builder provides a flexible, and also fluent, way to create SQL queries. It provides an intuitive way to create SQL queries with nearly all of the flexibility of using SQL direct.

Making my way through learning Laravel, most of the videos and articles I read focused on using Eloquent for database access. However, I found that using Eloquent for generating JSON, at least for some tasks, limited the control I had over how result set JSON was generated. This article shows how I turned to the Query Builder for generating the result sets to be expressed as JSON.

As I make my way further into Laravel, I am sure there will tasks for which Eloquent is superbly suited. However, I learned this weekend that there are also tasks for which the Query Builder is superbly suited.

Using Eloquent ORM

This Eloquent code (assuming the corresponding Laravel relations have been established)

produces this JSON:

Notice how the data from the related tables is placed into seperate JSON nodes (ie, the category, state, and type nodes). Unless you use the $hidden array in a model definition, there isn’t a way to limit the columns returned from related tables. The $hidden array can’t be changed at runtime so it must be specified in the model. Thus you either need special-cased models or learn to live with all of the columns being returned for related tables.

Laravel’s Query Builder to the rescue

Using Laravel’s Query Builder, you can get much less verbose JSON. The following query

produces this JSON. The Query Builder provides a greater level of control over what is included in the query. For example, note how you can use the ‘as’ clause in the select() method to alias result columns.


One comment on “Laravel’s Eloquent ORM versus Query Builder

  • Thanks for your article.

    I’ve also noticed a lot of tutorials prefer using Eloquent ORM, this might be for good practice for larger projects but I’ve noticed myself using Query Builder more often for simple MySQL statements.


Leave a Reply

Your email address will not be published. Required fields are marked *