Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
iserter avatar

Eloquent Best Practices

  • 1.2k installs
  • 42 repo stars
  • Updated April 19, 2026
  • iserter/laravel-claude-agents

eloquent-best-practices provides documented workflows for Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

About

The eloquent-best-practices skill best practices for Laravel Eloquent ORM including query optimization relationship management and avoiding common pitfalls like N 1 queries 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

  • [ ] Relationships eagerly loaded where needed
  • [ ] Only selecting required columns
  • [ ] Using query scopes for reusability
  • [ ] Mass assignment protection configured
  • [ ] Appropriate casts defined

Eloquent Best Practices by the numbers

  • 1,175 all-time installs (skills.sh)
  • +14 installs in the week ending Aug 5, 2026 (Skillselion tracking)
  • Ranked #82 of 911 Databases skills by installs in the Skillselion catalog
  • Security screen: MEDIUM risk (skills.sh audit)
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
At a glance

eloquent-best-practices capabilities & compatibility

Capabilities
[ ] relationships eagerly loaded where needed · [ ] only selecting required columns · [ ] using query scopes for reusability · [ ] mass assignment protection configured · [ ] appropriate casts defined
Use cases
documentation
From the docs

What eloquent-best-practices says it does

# Eloquent Best Practices ## Query Optimization ### Always Eager Load Relationships ```php // ❌ N+1 Query Problem $posts = Post::all(); foreach ($posts as $post) { echo $p
SKILL.md
npx skills add https://github.com/iserter/laravel-claude-agents --skill eloquent-best-practices

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs1.2k
repo stars42
Security audit3 / 3 scanners passed
Last updatedApril 19, 2026
Repositoryiserter/laravel-claude-agents

How do I use eloquent-best-practices for the task described in its SKILL.md triggers?

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

Who is it for?

Teams invoking eloquent-best-practices when the user request matches documented triggers and prerequisites.

Skip if: Skip when cached docs are missing, the request is a negative trigger, or another sibling skill owns the workflow.

When should I use this skill?

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

What you get

Step-by-step guidance grounded in eloquent-best-practices documentation and reference files.

  • optimized Eloquent query snippets
  • relationship loading patterns
  • scope convention examples

Files

SKILL.mdMarkdownGitHub ↗

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
}

Select Only Needed Columns

// ❌ 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

// ✅ 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

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 withCount for Counts

// ❌ Triggers additional queries
foreach ($posts as $post) {
    echo $post->comments()->count();
}

// ✅ Load counts efficiently
$posts = Post::withCount('comments')->get();
foreach ($posts as $post) {
    echo $post->comments_count;
}

Mass Assignment Protection

class Post extends Model
{
    // ✅ Whitelist fillable attributes
    protected $fillable = ['title', 'content', 'status'];
    
    // Or blacklist guarded attributes
    protected $guarded = ['id', 'user_id'];
    
    // ❌ Never do this
    // protected $guarded = [];
}

Use Casts for Type Safety

class Post extends Model
{
    protected $casts = [
        'published_at' => 'datetime',
        'metadata' => 'array',
        'is_featured' => 'boolean',
        'views' => 'integer',
    ];
}

Chunking for Large Datasets

// ✅ Process in chunks to save memory
Post::chunk(200, function ($posts) {
    foreach ($posts as $post) {
        // Process each post
    }
});

// ✅ Or use lazy collections
Post::lazy()->each(function ($post) {
    // Process one at a time
});

Database-Level Operations

// ❌ Slow - loads into memory first
$posts = Post::where('status', 'draft')->get();
foreach ($posts as $post) {
    $post->update(['status' => 'archived']);
}

// ✅ Fast - single query
Post::where('status', 'draft')->update(['status' => 'archived']);

// ✅ Increment/decrement
Post::where('id', $id)->increment('views');

Use Model Events Wisely

class Post extends Model
{
    protected static function booted()
    {
        static::creating(function ($post) {
            $post->slug = Str::slug($post->title);
        });
        
        static::deleting(function ($post) {
            $post->comments()->delete();
        });
    }
}

Common Pitfalls to Avoid

Don't Query in Loops

// ❌ Bad
foreach ($userIds as $id) {
    $user = User::find($id);
}

// ✅ Good
$users = User::whereIn('id', $userIds)->get();

Don't Forget Indexes

// Migration
Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->index();
    $table->string('slug')->unique();
    $table->string('status')->index();
    $table->timestamp('published_at')->nullable()->index();
    
    // Composite index for common queries
    $table->index(['status', 'published_at']);
});

Prevent Lazy Loading in Development

// In AppServiceProvider boot method
Model::preventLazyLoading(!app()->isProduction());

Checklist

  • [ ] Relationships eagerly loaded where needed
  • [ ] Only selecting required columns
  • [ ] Using query scopes for reusability
  • [ ] Mass assignment protection configured
  • [ ] Appropriate casts defined
  • [ ] Indexes on foreign keys and query columns
  • [ ] Using database-level operations when possible
  • [ ] Chunking for large datasets
  • [ ] Model events used appropriately
  • [ ] Lazy loading prevented in development

Related skills

How it compares

Use eloquent-best-practices during Laravel authoring; Telescope or Debugbar help diagnose queries already written without guiding correct Eloquent patterns upfront.

FAQ

What does eloquent-best-practices do?

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

When should I use eloquent-best-practices?

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

What are common prerequisites?

--- name: eloquent-best-practices description: Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

Is Eloquent Best Practices safe to install?

skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

Databasesdatabasespipelines

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.