Courses

Laravel 12 Eloquent: Expert Level

Eloquent vs Query Builder: whereHas vs join() vs Raw SQL

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Eloquent performs two queries vs one JOIN in Query Builder
- Query Builder uses less memory and executes faster
- whereHas() is slower than direct JOIN
- Raw SQL performance matches Query Builder

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

While Eloquent provides powerful features, Query Builder offers more direct control over SQL queries, with potentially better performance.

This lesson will compare them through practical examples.


Example Project

For our comparison, we'll use a simple database structure with:

  • 10,000 users
  • 3 posts per user (30,000 posts total)

We'll measure the performance of similar operations using both methods and analyze the results using Laravel Debugbar.


Retrieving Posts with Their Users

Approach 1: Using Eloquent Relationships

$posts = Post::with('user')
->where('title', 'like', '%a%')
->get();

When we execute this code and check the debugbar, we see:

  • 38,000 models loaded (posts + their users)
  • 77 MB of RAM used
  • 0,24 seconds execution time
  • 2 database queries

It's important to note how Eloquent handles this operation. Instead of using...

The full lesson is only for Premium Members.
Want to access all 38 video+text lessons of this course? (1 h 34 min)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord