Icaro William Icaro William
πŸ‡ΊπŸ‡Έ EN
Back

Eloquent Best Practices

I
Icaro William
| Feb 22, 2026 | PHP

Eloquent Best Practices

Eloquent ORM is one of the most powerful features of Laravel.

Use Query Scopes

Keep your queries clean with scopes:

class Post extends Model
{
    public function scopePublished(Builder $query): Builder
    {
        return $query->where('status', PostStatus::Published);
    }
}

// Usage
$posts = Post::query()->published()->get();

Always Eager Load

Prevent N+1 queries:

// Bad - N+1 problem
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->category->name; // Extra query each time!
}

// Good - eager loading
$posts = Post::with('category')->get();

Use Model::query()

Always use Model::query() for better IDE support:

// Preferred
Post::query()->where('status', 'published')->get();

// Instead of
Post::where('status', 'published')->get();

Tags

Eloquent Performance