Bitcoscript
Database & Eloquent ORM

Query Builder vs Eloquent: When to Use Which

Query Builder vs Eloquent: When to Use Which

In this article, we'll compare Eloquent and the Query Builder side by side, and walk through practical guidelines for choosing between them.

1 views

Introduction

In the previous article, we introduced Eloquent and saw how it lets you interact with your database using clean, expressive PHP syntax. But Eloquent isn't actually the thing doing the database querying under the hood — it's built on top of another Laravel feature called the Query Builder, which you can also use directly, independent of any Eloquent model.

This raises a natural question for beginners: if Eloquent is so convenient, why would you ever use the Query Builder directly instead? As it turns out, both tools have their place, and understanding when to reach for each one is an important part of writing efficient, appropriate Laravel code.

In this article, we'll compare Eloquent and the Query Builder side by side, and walk through practical guidelines for choosing between them.

What is the Query Builder?

The Query Builder is Laravel's lower-level, fluent interface for constructing SQL queries using PHP method chains, without needing a corresponding Eloquent model. You access it through the DB facade.

php

use Illuminate\Support\Facades\DB;

$posts = DB::table('posts')->get();

This looks strikingly similar to Eloquent syntax, and that's not a coincidence — Eloquent actually uses the Query Builder internally to construct its own queries. The key difference is that Query Builder results come back as plain PHP objects (specifically, stdClass instances) rather than full Eloquent model instances.

Side-by-Side Comparison

Retrieving Records

Eloquent:

php

$posts = Post::where('is_published', true)->get();

Query Builder:

php

$posts = DB::table('posts')->where('is_published', true)->get();

Notice how nearly identical the syntax is — this is intentional, since Eloquent's query methods are built directly on top of the Query Builder's fluent interface.

Inserting Records

Eloquent:

php

Post::create(['title' => 'New Post', 'body' => 'Content here']);

Query Builder:

php

DB::table('posts')->insert(['title' => 'New Post', 'body' => 'Content here']);

Updating Records

Eloquent:

php

Post::where('id', 1)->update(['title' => 'Updated Title']);

Query Builder:

php

DB::table('posts')->where('id', 1)->update(['title' => 'Updated Title']);

Deleting Records

Eloquent:

php

Post::where('id', 1)->delete();

Query Builder:

php

DB::table('posts')->where('id', 1)->delete();

Key Differences Beyond Syntax

Return Types

Eloquent queries return actual model instances, giving you access to relationships, accessors/mutators (covered in a later article), and any custom logic defined on the model. Query Builder results are plain generic objects, with none of that additional model behavior attached.

php

$post = Post::find(1);
echo $post->formatted_date; // Works, if defined as an accessor on the model

$post = DB::table('posts')->find(1);
echo $post->formatted_date; // Doesn't exist — plain object has no model logic

Performance

Since Eloquent adds a layer of object hydration and model-related processing on top of the Query Builder, it carries slightly more overhead than using the Query Builder directly. For the vast majority of applications, this difference is negligible — but for very large, performance-critical queries (like processing hundreds of thousands of rows), the Query Builder's lighter weight can matter.

Relationships

Eloquent's relationship system (which we'll explore in depth in the next article) is one of its biggest advantages — allowing you to easily retrieve related data, like a post's author or comments, with simple, readable syntax:

php

$post = Post::with('author')->find(1);
echo $post->author->name;

The Query Builder has no concept of relationships at all — you'd need to write manual joins yourself to achieve the same result.

When to Use Eloquent

Eloquent is the right choice for the vast majority of everyday application code, especially when:

  • You need to work with model relationships (posts belonging to users, comments belonging to posts, etc.).

  • You want to use accessors, mutators, or other custom model logic.

  • You're building typical CRUD functionality for your application's resources.

  • Code readability and maintainability matter more than squeezing out maximum query performance.

When to Use the Query Builder Directly

The Query Builder becomes the better choice in more specific situations:

  • Complex reporting queries that don't map cleanly to a single model, such as aggregating data across multiple unrelated tables.

  • Performance-critical operations involving very large datasets, where the overhead of model hydration becomes meaningful.

  • One-off scripts or maintenance tasks that just need to read or modify raw data without any model-related behavior.

  • Queries that don't correspond to any specific model at all, such as querying a pivot table or a table with no dedicated Eloquent model.

php

$totalRevenue = DB::table('orders')
    ->join('order_items', 'orders.id', '=', 'order_items.order_id')
    ->sum('order_items.price');

Mixing Both Approaches

It's also worth knowing that you can access the underlying Query Builder from within an Eloquent model when needed, giving you flexibility without fully abandoning Eloquent:

php

$titles = Post::query()->pluck('title');

This still benefits from Eloquent's model context (like global scopes, if defined) while behaving similarly to a direct Query Builder call.

Tips for Choosing Between Eloquent and Query Builder

  1. Default to Eloquent for standard application code — it's more readable, integrates with relationships, and fits Laravel's conventions.

  2. Reach for the Query Builder when a query doesn't map well to a single model, or when you need raw performance for very large datasets.

  3. Don't prematurely optimize by avoiding Eloquent "for performance reasons" unless you've actually identified a real bottleneck — for most applications, the difference is imperceptible.

  4. Use DB::table() for quick, one-off queries in scripts or command-line tasks that don't need full model behavior.

  5. Remember both share the same fluent query syntax, so switching between them when needed doesn't require learning an entirely different approach.

FAQ About Query Builder vs Eloquent

1. Is Eloquent just the Query Builder with extra features? Essentially, yes. Eloquent is built directly on top of the Query Builder, adding model hydration, relationships, and additional conveniences on top of the same underlying query construction logic.

2. Will switching from Eloquent to the Query Builder make my application noticeably faster? For most typical applications, no — the difference is usually too small to notice. It only becomes meaningful for very large-scale queries or performance-critical operations.

3. Can I use the Query Builder without having any Eloquent models defined at all? Yes. DB::table('table_name') works independently of Eloquent, and doesn't require a corresponding model class to exist.

4. Do Query Builder results support pagination like Eloquent does? Yes, the Query Builder supports the same paginate() method that Eloquent does, since pagination is implemented at the Query Builder level and inherited by Eloquent.

5. Can I run raw SQL if neither Eloquent nor the Query Builder covers what I need? Yes, Laravel also supports raw SQL queries directly through DB::select(), DB::insert(), and similar methods, for the rare cases where neither fluent approach fits your needs.

6. Is it bad practice to mix Eloquent and Query Builder in the same application? Not at all. Many real-world Laravel applications use Eloquent for the majority of their code, while reaching for the Query Builder in specific spots, like complex reports or performance-sensitive operations.

Conclusion

Eloquent and the Query Builder aren't competing tools — they're complementary layers, with Eloquent building directly on top of the Query Builder's foundation. For most application code, Eloquent's readability and relationship support make it the natural default, while the Query Builder remains available for the specific cases where its lighter weight or flexibility is genuinely needed.

In the next article, we'll dive into one of Eloquent's most powerful features: relationships, covering one-to-one, one-to-many, and many-to-many associations between your models.

Found this helpful? Share it!

Tweet

Comments

Leave a Comment