$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[September 24, 2026] Eloquent ORM

Eloquent Advanced Where Clauses

Eloquent Advanced Where Clauses

────────────────────────────────────────────────────────

Eloquent Advanced Where Clauses

Tip: Where Grouping

Post::where(function ($q) {
    $q->where('published', true)
      ->orWhere('draft', true);
})->where('category_id', 1)->get();

Gotcha: orWhere Without Grouping

Post::where('category_id', 1)->orWhere('featured', true)->get();

This returns posts in category 1 OR all featured posts (not what you want).

Tip: when() for Conditional Where

Post::when($request->category, fn($q) => $q->where('category_id', $request->category))->get();

Gotcha: whereNull and whereNotNull

Post::whereNull('deleted_at')->whereNotNull('published_at')->get();

Tip: whereBetween

Post::whereBetween('views', [100, 1000])->get();

Gotcha: Raw Where Clauses

Post::whereRaw('YEAR(created_at) = ?', [2024])->get();

Tip: Use cursor() for Memory-Neutral Iteration

When exporting 100K rows, get() loads everything into memory. cursor() uses yield and keeps memory flat regardless of row count. Perfect for artisan commands.

Tip: whereHas() vs load() — Two Different Things

whereHas() filters the parent query by relationship existence. load() eager-loads relationships AFTER the query. Mixing them up is a common source of logic bugs.

Gotcha: withCount() Adds a Subquery

withCount('comments') runs a correlated subquery on every row. On large tables, this can be slower than a separate query. Profile before relying on it.

Senior Insight

Eloquent is Laravel's most controversial feature — developers either love its convenience or hate its magic. My take after years of using both Eloquent and raw SQL: Eloquent is excellent for 80% of queries and wrong for the other 20%. The skill is knowing which is which. If a query involves more than three joins, window functions, or complex subqueries, reach for the Query Builder or raw SQL. Eloquent's beauty is in its simplicity for CRUD; fighting it for complex queries helps no one.

Source: Laravel Docs (https://laravel.com/docs/eloquent), Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/eloquent)

────────────────────────────────────────────────────────
<-- back to posts