Eloquent Best Practices
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();