eloquent-best-practices
Laravel Eloquent query optimization and relationship management patterns with N+1 prevention.
- Eager load relationships with
with()and usewithCount()for efficient aggregations instead of triggering additional queries in loops - Select only needed columns at query time and define return types on relationship methods for better IDE support and clarity
- Use query scopes to encapsulate reusable filtering logic and leverage database-level operations (
update(),increment()) instead of loading models into memory - Implement mass assignment protection via
$fillableor$guarded, define type casts for safety, and chunk large datasets to manage memory efficiently - Add database indexes on foreign keys and frequently queried columns, and enable lazy loading prevention in development to catch N+1 issues early
Eloquent Best Practices
Query Optimization
Always Eager Load Relationships
// ❌ 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
}
More from iserter/laravel-claude-agents
laravel-tdd
Test-Driven Development specifically for Laravel applications using Pest PHP. Use when implementing any Laravel feature or bugfix - write the test first, watch it fail, write minimal code to pass.
269api-resource-patterns
Best practices for Laravel API Resources including resource transformation, collection handling, conditional attributes, and relationship loading.
110systematic-debugging-laravel
Systematic debugging process for Laravel applications - ensures root cause investigation before attempting fixes. Use for any Laravel issue (test failures, bugs, unexpected behavior, performance problems).
82brainstorming-laravel
Use when creating or developing Laravel features, before writing code or implementation plans - refines rough ideas into fully-formed Laravel designs through collaborative questioning, alternative exploration, and incremental validation.
80laravel-validation-patterns
Best practices for Laravel validation including Form Requests, custom rules, conditional validation, and input sanitization.
47laravel-systematic-debugging
Systematic debugging process for Laravel applications - ensures root cause investigation before attempting fixes. Use for any Laravel issue (test failures, bugs, unexpected behavior, performance problems).
46