← ClaudeAtlas

eloquent-best-practiceslisted

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.
rcdelfin/agentkit · ★ 1 · AI & Automation · score 74
Install: claude install-skill rcdelfin/agentkit
# Eloquent Best Practices ## Query Optimization ### Always Eager Load Relationships ```php // ❌ N+1 Query Problem $posts = Post::all(); foreach ($posts as $post) { echo $post->user->name; // N additional queries } // ✅ Eager Loading $posts = Post::with('user')->get(); foreach ($posts as $post) { echo $post->user->name; // No additional queries } ``` ### Select Only Needed Columns ```php // ❌ Fetches all columns $users = User::all(); // ✅ Only needed columns $users = User::select(['id', 'name', 'email'])->get(); // ✅ With relationships $posts = Post::with(['user:id,name'])->select(['id', 'title', 'user_id'])->get(); ``` ### Use Query Scopes ```php // ✅ Define reusable query logic class Post extends Model { public function scopePublished($query) { return $query->where('status', 'published') ->whereNotNull('published_at'); } public function scopePopular($query, $threshold = 100) { return $query->where('views', '>', $threshold); } } // Usage $posts = Post::published()->popular()->get(); ``` ## Relationship Best Practices ### Define Return Types ```php use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; class Post extends Model { public function user(): BelongsTo { return $this->belongsTo(User::class); } public function comments(): HasMany { return $this->hasMany(Comment::class); } } ``` ### Use