Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jimmck's avatar
Level 13

Eager Loading

A note before I ask. I don't use Eloquent, simply because I have a library that works well for me. I ported it over from JAVA as a project to learn about PHP's OOP capabilities. That being said I would like to at least understand a package that fills this forum. So I kept seeing post after post about eager loading. Well I was tending to think, well eager loading, oh that must be querying a large record set and returning workable chunks. You know how some one can build meaningful screens and such. So I looked it up in the docs and saw the 'N + 1' problem, hmm. Are we dealing with a physics question here? So I read on. In the example, the documentation is woefully brief on how the API's work, is the example of the problem of books and authors and how Eager Loading will remove duplicate (N + 1) queries. I read this again. So then I read a code snippit.

select * from books

select * from authors where id in (1, 2, 3, 4, 5, ...)

I was astonished? We removed multiple queries of select from Books and then select from Authors. Ok good, but we are coding Join logic that can be done inside the database query, by the SQL engine. Why? Why are we not just Joining Books and Authors by id?

Eager Loading would make sense if I was Joining tables from two totally different, separate databases. But two tables? At a minimum if there is no common id field, any competent database design would refactor it in.

Eloquent's Query Builder even has join commands. So why even introduce the idea of Eager Loading as solution to the 'N + 1' problem?

Am I missing some obvious distinction, perhaps clouded by years of database development in many languages and environments?

0 likes
3 replies
jimmck's avatar
Level 13

Sorry this post did not hit the forum?

Francismori7's avatar

Thing is Eloquent is there to make your life easier - Taylor did mention that I think. You can easily do this yourself with DB::select and DB::join if you prefer, which is what I do myself in most cases.

Or did you mean foreign keys automation like InnoDB?

jimmck's avatar
Level 13

Hi @VFrancismori7 I prefer to do it as efficiently as possible. Let the database do the work, its usually faster and less code for you to maintain.

Please or to participate in this conversation.