$ lexprog.com

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

[October 30, 2026] Eloquent ORM

Eloquent Query Scopes: Reusability

Eloquent Query Scopes: Reusability

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

Eloquent Query Scopes: Reusability

Tip: Basic Scope

public function scopePublished(Builder $query): Builder
{
    return $query->whereNotNull('published_at');
}

Gotcha: Scope Parameters

public function scopeOfType(Builder $query, string $type): Builder
{
    return $query->where('type', $type);
}

Tip: Chain Scopes

Post::published()->featured()->recent()->get();

Gotcha: Scope in Relationships

public function publishedPosts(): HasMany
{
    return $this->hasMany(Post::class)->published();
}

Tip: Local Scope Trait

trait HasPublishedScope
{
    public function scopePublished(Builder $query): Builder
    {
        return $query->whereNotNull('published_at');
    }
}

Gotcha: Scope Returns Builder

Always return $query to enable chaining.

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