Eloquent Is Lying to You About Your Database Performance

D
Dick Edidiong Bassey
·

Eloquent makes database access feel magical. It is also responsible for a significant share of N+1 query bugs in production systems.

The N+1 problem: you query 100 orders. Eloquent loads them. For each, it issues a separate query to load the related customer. That is 101 database queries where 2 would suffice.

The fix is eager loading — Model::with(['customer'])->get() — but it is invisible until you enable query logging.

Rule: always enable query logging in development. Always eager-load relationships you will access. For complex reporting, write raw SQL with explicit joins.

— Dick Bassey | DevDick | 2021